How to use "OR" using Django's model filter system?
Asked Answered
C

2

42

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 OR? I can't seem to find it in the documentation (oddly enough, searching for 'or' isn't really useful).

Cimabue answered 2/7, 2010 at 14:0 Comment(0)
C
83

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"))
Cly answered 2/7, 2010 at 14:2 Comment(0)
M
1

Without Q(), you can also run OR operater as shown below:

Publisher.objects.filter(name__contains="press") | \
Publisher.objects.filter(country__contains="U.S.A")
Merocrine answered 23/12, 2022 at 4:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.