Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use OR using Django's model filter system?

Tags:

python

sql

django

It seems that Django's object model filter method automatically uses the AND SQL keyword.

For example:

>>> Publisher.objects.filter(name__contains="press", country__contains="U.S.A")

will automatically translate into something like:

SELECT ... 
FROM publisher
WHERE name LIKE '%press%'
AND country LIKE '%U.S.A.%'

However, I was wondering whether there was a way to make that 'AND' an 'OR'? I can't seem to find it in the documentation (oddly enough, searching for 'or' isn't really useful).

like image 450
NotSimon Avatar asked Jul 02 '10 14:07

NotSimon


People also ask

What is 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.

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


1 Answers

You can use Q objects to do what you want, by bitwise OR-ing them together:

from django.db.models import Q
Publisher.objects.filter(Q(name__contains="press") | Q(country__contains="U.S.A"))
like image 198
Will McCutchen Avatar answered Oct 28 '22 16:10

Will McCutchen