Django 'objects.filter()' with list?

邮差的信 提交于 2019-12-29 17:44:12

问题


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

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

???


回答1:


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.




回答2:


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)
        ...


来源:https://stackoverflow.com/questions/5956391/django-objects-filter-with-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!