Simon Simon - 1 year ago 76
Python Question

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

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:

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

Answer Source

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"))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download