Django 'objects.filter()' with list?

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

You mean like this?

my_model.objects.filter(creator__in=creator_list) 

Docs:

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.

9

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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like