如何在Django中动态组成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)

以上是 如何在Django中动态组成OR查询过滤器? 的全部内容, 来源链接: utcz.com/qa/404821.html

回到顶部