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

从示例中,您可以看到多个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))


jeck猫
浏览 824回答 3
3回答

HUX布斯

您可以按如下方式链接查询:values = [1,2,3]# Turn list of values into list of Q objectsqueries = [Q(pk=value) for value in values]# Take one Q object from the listquery = queries.pop()# Or the Q object with the ones remaining in the listfor item in queries:&nbsp; &nbsp; query |= item# Query the modelArticle.objects.filter(query)

慕姐8265434

要构建更复杂的查询,还可以选择使用内置的Q()对象的常量Q.OR和Q.AND以及add()方法,如下所示:list = [1, 2, 3]# it gets a bit more complicated if we want to dynamically build# OR queries with dynamic/unknown db field keys, let's say with a list# of db fields that can change like the following# list_with_strings = ['dbfield1', 'dbfield2', 'dbfield3']# init our q objects variable to use .add() on itq_objects = Q()# loop trough the list and create an OR condition for each itemfor item in list:&nbsp; &nbsp; q_objects.add(Q(pk=item), Q.OR)&nbsp; &nbsp; # for our list_with_strings we can do the following&nbsp; &nbsp; # q_objects.add(Q(**{item: 1}), Q.OR)queryset = Article.objects.filter(q_objects)# sometimes the following is helpful for debugging (returns the SQL statement)# print queryset.query
打开App,查看更多内容
随时随地看视频慕课网APP