使用Django的模型过滤系统如何使用OR? [英] How to use OR using Django's model filter system?

查看:135
本文介绍了使用Django的模型过滤系统如何使用OR?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎Django的对象模型过滤器方法自动使用AND SQL关键字。

It seems that Django's object model filter method automatically uses the AND SQL keyword.

例如:

>>> Publisher.objects.filter(name__contains="press", country__contains="U.S.A")

将自动翻译如下:

SELECT ... 
FROM publisher
WHERE name LIKE '%press%'
AND country LIKE '%U.S.A.%'

然而,我想知道是否有使AND成为OR的方法?我似乎没有在文档中找到它(奇怪的是,搜索或并不真正有用)。

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

推荐答案

您可以使用 Q对象通过按位或者将它们合并在一起来做你想要的:

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

这篇关于使用Django的模型过滤系统如何使用OR?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆