总是假Q对象 [英] Always False Q object

查看:129
本文介绍了总是假Q对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Django ORM中,如何创建始终为False的Q对象?

In Django ORM, how does one go about creating a Q object that is always False?

这与对齐True Q对象,但另一方面。

请注意,这不工作:

Foobar.objects.filter(~Q()) # returns a queryset which gives all objects






为什么我想要一个Q对象而不是简单的False值?所以我可以把它与其他Q值结合起来,例如:


Why do I want a Q object instead of the simple False value? So that I can combine it with other Q values, like this for example:

condition = always_true_q_object
if something_or_other:
    condition = condition | foobar_that_returns_a_q_object()
if something_or_other2:
    condition = condition | foobar_that_returns_a_q_object2()


推荐答案

b
$ b

What about:

Q(pk__isnull=True)

Q(pk=None)

看起来很糟糕,但它似乎工作。例如:

It seems hacky, but it appears to work. For example:

>>> FooBar.objects.filter(Q(x=10)|Q(pk__isnull=True))
[<FooBar: FooBar object>, ...]
>>> FooBar.objects.filter(Q(x=10)&Q(pk__isnull=True))
[]

但是,请注意,当您使用空的 Q()

However, note that it doesn't work as you might expect when OR'd with an empty Q().

>>> FooBar.objects.filter(Q()|Q(pk__isnull=True))
[]

解决方案可能是使用 Q(pk__isnull = False)作为永远是真的Q。

The solution to this might be to use Q(pk__isnull=False) as the 'always True Q'.

>>> FooBar.objects.filter(Q(pk__isnull=False)|Q(pk__isnull=True))
[<FooBar: FooBar object>, ...]
>>> FooBar.objects.filter(Q(pk__isnull=False)&Q(pk__isnull=True))
[]

这篇关于总是假Q对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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