How do I create a Django queryset equivalent to a SQL query using the OR operator?
-
05-07-2019 - |
Question
In Django, I know using filter
with multiple arguments gets translated into SQL AND
clauses. From the Django Book:
You can pass multiple arguments into filter() to narrow down things further:
>>> Publisher.objects.filter(country="U.S.A.", state_province="CA") [<Publisher: Apress>]
Those multiple arguments get translated into SQL AND clauses. Thus, the example in the code snippet translates into the following:
SELECT id, name, address, city, state_province, country, website FROM books_publisher WHERE country = 'U.S.A.' AND state_province = 'CA';
How do I create a Django queryset that gets translated into SQL OR
clauses? For example:
SELECT id, name, address, city, state_province, country, website
FROM books_publisher
WHERE state_province = 'AZ'
OR state_province = 'CA';
Solution
using the Q operator available in django.db.models
IE:
from django.db.models import Q
Publisher.objects.filter(Q(state_province="CA") | Q(state_province="AZ"))
Have a look in the docs here: http://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow