python - Django 组合多个查询集(相同模型)

标签 python django django-models

我有查询集列表(全部用于同一模型):

results = Entry.objects.all()
result_elms = []
if city_list:
    for city in city_list:
    result_elms.append(results.filter(address__city__icontains=city))

if county_list:
    for county in county_list:
        results_elms.append(results.filter(address__county__icontains=county))
#other filters here, daynamically created

#how can I combine all results_elms (querysets) into one?

我知道我可以使用 | 运算符来组合来自同一模型的查询集。 但是如何将它应用于 result_elms 列表中的所有元素?

最佳答案

您可以使用 Q 对象:

from django.db.models import Q

results = Entry.objects.all()
q = Q()
for city in city_list:
    q = q | Q(address__city__icontains=city)
results.filter(q)

文档 ( https://docs.djangoproject.com/en/1.7/topics/db/queries/#complex-lookups-with-q ) 包含更多详细信息和示例。

关于python - Django 组合多个查询集(相同模型),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47236667/

相关文章:

python - 将 pcollection 的每一行拆分为多个 pcollection?

python - Django 和 Oracle DB 失去联系

python - 我可以使用 Django 模型对数据库执行复杂查询吗?

python - 我是否需要安装 Hadoop 才能使用 Pyspark 的所有功能?

python - sklearn 交叉验证遇到 JoblibValueError

python - 如何从 (ba)sh 脚本导入变量?

python - Django 找不到 psycopg2 模块

python - "resolve_variable"在 Django 中做什么? ("template.Variable")

python - 模块未找到错误: No module named 'mysite' when try to call django-admin

database - 同步时模型不会创建表