Skip to main content
 首页 » 编程设计

python之如何在 Django 中动态组合 OR 查询过滤器

2025年05月04日38mq0036

从一个示例中,您可以看到多个 OR 查询过滤器:

Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3)) 

例如,这会导致:

[<Article: Hello>, <Article: Goodbye>, <Article: Hello and goodbye>] 

但是,我想从一个列表中创建这个查询过滤器。如何做到这一点?

例如[1, 2, 3] -> Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3))

请您参考如下方法:

您可以按如下方式链接您的查询:

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)