如何在 Django 中动态组合 OR 查询过滤器? [英] How to dynamically compose an OR query filter in Django?
本文介绍了如何在 Django 中动态组合 OR 查询过滤器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
从示例中您可以看到多个 OR 查询过滤器:
From an example you can see a multiple OR query filter:
Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3))
例如,这会导致:
[<Article: Hello>, <Article: Goodbye>, <Article: Hello and goodbye>]
但是,我想从列表中创建此查询过滤器.怎么做?
However, I want to create this query filter from a list. How to do that?
例如<代码>[1, 2, 3] ->Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3))
推荐答案
您可以按如下方式链接您的查询:
You could chain your queries as follows:
values = [1,2,3]
# Turn list of values into list of Q objects
queries = [Q(pk=value) for value in values]
# Take one Q object from the list
query = queries.pop()
# Or the Q object with the ones remaining in the list
for item in queries:
query |= item
# Query the model
Article.objects.filter(query)
这篇关于如何在 Django 中动态组合 OR 查询过滤器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文