Python/Django-"and"和"and"之间有什么区别运算符和“&"操作员 [英] Python/Django -- what is the difference between the "and" operator and the "&" operator

查看:113
本文介绍了Python/Django-"and"和"and"之间有什么区别运算符和“&"操作员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个有趣的Django问题.

I have a interesting Django problem.

请考虑以下内容:

Model.objects.filter(Q(id='test1') and Q(id='test2'))

这将返回预期结果,但是

this returns the expected results, however

Model.objects.filter(Q(id='test1') & Q(id='test2'))

没有!

这是怎么回事?

推荐答案

如果您希望Django ORM返回test1和test2,则应使用:

If you want Django ORM to return test1 and test2, you should use :

Model.objects.filter(Q(id='test1') | Q(id='test2'))

Model.objects.filter(Q(id='test1') & Q(id='test2'))表示同时返回其id为test2和id为test1的返回模型对象.当然,django将返回一个空的QuerySet.

Model.objects.filter(Q(id='test1') & Q(id='test2')) means return model objects whose id is test1 while its is test2 at the same time. Of course, django will return an empty QuerySet.

and is a boolean operator in Python. For operation x and y the result is if x is false, then x, else y. Thus Q(id='test1') and Q(id='test2') equals Q(id='test1'), it is not what you want.

&/| 按位和/或运算符.

顺便说一句,无法覆盖布尔运算符,但是您可以通过定义名为__and__/__or__的方法来覆盖类中的&/|运算符.

BTW, there's no way to override the boolean operator, but you can override &/| operators in your class by define a method named __and__ / __or__.

以下是django Q对象的源代码 [github] :

below is the source code of the django Q object[github]:

class Q(tree.Node):
    """
    Encapsulates filters as objects that can then be combined logically (using
    & and |).
    """
    # Connection types
    AND = 'AND'
    OR = 'OR'
    default = AND

    def __or__(self, other):
        return self._combine(other, self.OR)

    def __and__(self, other):
        return self._combine(other, self.AND)
    ...

这篇关于Python/Django-"and"和"and"之间有什么区别运算符和“&"操作员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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