在djnago中过滤queryset,其中一个字段具有特定值或为null
在django中做到这一点的正确方法是什么,我想过滤一个字段具有特定值或为null的QuerySet,这意味着,如果我按名为“类型”的字段过滤QuerySet,它将返回带有对象的QuerySet具有类型的特定值,例如“ Active”,并且具有“类型”的对象具有空值。
what's the right way to do this in Django, i want to to filter a queryset where the field has a specific value or is null,which means that if i filter a queryset by field named "type", it would return a queryset with objects has a specific value of type like "active" and also object with "type" has null value.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以与 q 对象  [django-doc] 为此:
在这里,我们将两个
q
对象组合在一起,它们充当过滤器使用位或操作员|
,这意味着我们可以创建一个用作逻辑或两个过滤器条件之间的过滤器。You can work with
Q
objects [Django-doc] for this:Here we combine the two
Q
objects, which act as filters with a bitwise or operator|
, and this means that we create a filter that acts as a logical or between the two filter conditions.DJANGO文档中有一个部分与模型现场查找。但是,如果您不想弄乱它,这里有一些例子:
您可能想处理更多的事情,但我认为我描述了最常见的用例。
编辑
正如Willem答案中所写的,以获取具有“活动”或null值的行,您应该编写此类查询:
There is a whole section in Django documentation related to model field lookups. But if you don't want to mess with it here is some examples:
There are a lot more things that you may want to do with your field, but I think that I described the most common use case.
Edit
As written in the Willem's answer to obtain rows that has value of "active" or null you should write such query:
我认为这是实现您目标的最简单技术。
I think this is the simplest technique to achieve your aim.