Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) 

???

like image 486
krzyhub Avatar asked May 10 '11 20:05

krzyhub


People also ask

How can I filter a Django query with a list of values?

To filter a Python Django query with a list of values, we can use the filter method with in . to search Blog entries with pk set to 1,4 or 7 by calling Blog. objects. filter with the pk_in argument set to [1, 4, 7] .

What is objects filter in Django?

The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.

What is Queryset in Django?

A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.


1 Answers

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.

like image 192
Bryce Siedschlaw Avatar answered Sep 26 '22 06:09

Bryce Siedschlaw