在Django中,我知道使用filter
将多个参数转换为SQL AND
子句。来自Django书:
您可以传递多个参数 filter()缩小范围 进一步:
>>> Publisher.objects.filter(country="U.S.A.", state_province="CA") [<Publisher: Apress>]
获得那些多个参数 翻译成SQL AND子句。从而, 代码段中的示例 转化为以下内容:
SELECT id, name, address, city, state_province, country, website FROM books_publisher WHERE country = 'U.S.A.' AND state_province = 'CA';
如何创建一个转换为SQL OR
子句的Django查询集?例如:
SELECT id, name, address, city, state_province, country, website
FROM books_publisher
WHERE state_province = 'AZ'
OR state_province = 'CA';
答案 0 :(得分:21)
使用django.db.models中提供的Q运算符
IE:
from django.db.models import Q
Publisher.objects.filter(Q(state_province="CA") | Q(state_province="AZ"))
在这里查看文档:{{3}}