开发者

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

开发者 https://www.devze.com 2023-01-06 07:16 出处:网络
It seems that Django\'s object model filter method automatically uses the AND SQL keyword. For example:

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=&q开发者_JAVA技巧uot;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).


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


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")
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号