python - query.connector 的值如何设置在 Django 代码中的 Q 对象中?

标签 python django

在 django websie 开发过程中,我遇到了 django Q objects & query。

我有下面的代码。

我引用了官方文档 https://docs.djangoproject.com/en/2.2/topics/db/queries/ .

 query = Q()
    if request.POST.get('emp_name') != None:
        query.add(Q(emp_name__icontains=str(request.POST.get('emp_name'))), query.connector)

我知道 Query Q 对象的工作原理,但无法理解 query.connector 值的定义方式。

query.connector 值将类似于 'AND' , 'OR' 同样。

对于上述类型的问题,我无法获得任何在线引用。

最佳答案

简答:如果您自己不传递_connector。 Django 最终将使用 'AND' 作为连接器。

Q 对象是tree.Node 的子类。事实上,我们可以检查 source code [GitHub] :

class Q(tree.Node):
    """
    Encapsulate filters as objects that can then be combined logically (using
    `&` and `|`).
    """
    # Connection types
    AND = 'AND'
    OR = 'OR'
    <b>default = AND</b>
    conditional = True

    def __init__(self, *args, <b>_connector=None</b>, _negated=False, **kwargs):
        super().__init__(children=[*args, *sorted(kwargs.items())], connector=<b>_connector</b>, negated=_negated)

    # …

当我们构造一个 Q 对象时,我们对 tree.Node 数据构造函数进行 super 调用,如果我们不传递 _connector,它将取 None 作为值。

如果 connector 的真实性为 NoneNode 本身将采用默认值。事实上,如果我们看一下 source code of Node [GitHub] ,我们看到:

class Node:
    """
    A single internal node in the tree graph. A Node should be viewed as a
    connection (the root) with the children being either leaf nodes or other
    Node instances.
    """
    # Standard connector type. Clients usually won't use this at all and
    # subclasses will usually override the value.
    default = 'DEFAULT'

    def __init__(self, children=None, connector=None, negated=False):
        """Construct a new Node. If no connector is given, use the default."""
        self.children = children[:] if children else []
        <b>self.connector = connector or self.default</b>
        self.negated = negated

    # …

这意味着如果您构造一个Q 对象,则默认连接器是Q.AND 的值,因此是'AND' .

关于python - query.connector 的值如何设置在 Django 代码中的 Q 对象中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58144489/

相关文章:

python - 在 Pandas 中展平网格状数据框

django - 使用非托管模型转储数据

python - 属性错误 : 'bytes' object has no attribute 'find_all' after encoding in Python

django - 如何使用 wsgi_mod 在 ubuntu 中托管 django 项目

ruby-on-rails - 另一个Django v Rails问题-哪个更适合复杂的Web应用程序?

python - 当 virtualenv 和系统站点包有冲突的依赖关系时会发生什么?

python - Monkey Patching Exception 类和其他内置类

python - 如何在Python中对树莓派的GPIO输出值进行单元测试

python - 具有 '__in' 过滤器性能的 Django ORM values_list

Django admin 内联自定义查询集