在 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
的真实性为 None
,Node
本身将采用默认值。事实上,如果我们看一下 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/