Django 'objects.filter()' with list?

前端 未结 2 2264
醉梦人生
醉梦人生 2020-12-24 07:33

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

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


        
2条回答
  •  情书的邮戳
    2020-12-24 08:06

    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.

提交回复
热议问题