40

It is possible to limiting QuerySet in this kind of way:

creators_list = ['jane', 'tarzan', 'chita']
my_model.objects.filter(creator=creators_list)

???

2 Answers 2

75

You mean like this?

my_model.objects.filter(creator__in=creator_list)

Docs: http://docs.djangoproject.com/en/dev/ref/models/querysets/#in

EDIT

This is now a bit outdated. If you run into problems with the original code, try this:

from django.db.models import Q

my_filter_qs = Q()
for creator in creator_list:
    my_filter_qs = my_filter_qs | Q(creator=creator)
my_model.objects.filter(my_filter_qs)

There's probably a better way to do it but I'm not able to test it at the moment.

Sign up to request clarification or add additional context in comments.

9 Comments

Assuming of course that the creator field is a CharField of some sort
@Bryce: Isn't the blessing of the Universe enough ;)?
Do You assuming that there is something more than Universe?
Thanks for link to django's docs Bryce. I written this but in the past and my knowledge is better in one part of django, because of time flowing but I want to learn something from people like You in stright way:)
@Chris perhaps there is more then one Universe and perhaps we are just part of some multiverse :p, you never know.
|
1

Also if you're using sqlite and running into problems, there exists a limitation for the max number of items in the list.

def divideChunks(l, n):
    for i in range(0, len(l), n):
        yield l[i:i + n]

for slicerange in divideChunks(objs, 10):
        myobjects = my_model.objects.filter(creator__in = slicerange)
        ...

1 Comment

just a suggestion, never iterate on db... they have indexing and other features... that's why they are there for... they are not just array... way way more than that... this will dramatically reduce the performance... please check the answer below: stackoverflow.com/a/5956422/10305444

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.