python - 这个运算符在 django `reduce(operator.and_, query_list)` 中意味着什么

标签 python django django-queryset

我正在阅读这个问题

Constructing Django filter queries dynamically with args and kwargs

我不明白这个运算符(operator)在做什么

filter(reduce(operator.or_, argument_list))

或者这个

filter(reduce(operator.and_, query_list))

最佳答案

filter是Django Model Manager的常规方法,就不多解释了。

reduce 是一个类似于下面代码的内置函数:

def reduce(func, items):
    result = items.pop()
    for item in items:
        result = func(result, item)

    return result

其中 func 是用户定义的函数。

operator.or_ 是一个 python 标准库函数,它包装了 or 运算符。它类似于这段代码:

def or_(a, b):
    return a | b

例如:

reduce(operator.or_, [False, False, True])

将返回 True

在您的示例上下文中,orand 运算符被重载,因此它应该返回一个由较小部分组合而成的新查询,所有这些部分都由 orand 运算符。

关于python - 这个运算符在 django `reduce(operator.and_, query_list)` 中意味着什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16076894/

相关文章:

javascript - 在 django 中使用 javascript 进行 ajax 调用

Django ModelForm bool 字段在 True 时不给出 None

python - 我如何进行查询以过滤 Django 中以数字开头的所有内容?

mysql - Django queryset 选择在哪里连接

python - PyInstaller 和超过 8 个字符的 MEIPASS 文件夹

python - Django - 如何覆盖每个语言环境的默认日期格式?

django - 如何在models.py中的save方法中获取内联对象

Django:使用 Django ORM 实现 JOIN?

python - 如何用空白输入(str)结束 while 循环

python - 如何使用 Windows 运行 python 命令?