views:

480

answers:

1

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';
+10  A: 

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

Mike Scott
Great! This is what I was looking for. I think I've read that section of the docs, but I didn't find it today. Thank you.
saltycrane
No worries, have used it many, many times so it popped straight up in my head. :)
Mike Scott