为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

jeck猫 2019-09-19 15:25:17
从示例中,您可以看到多个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))
查看完整描述

3 回答

?
HUX布斯

TA贡献1876条经验 获得超6个赞

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


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)


查看完整回答
反对 回复 2019-09-19
?
慕姐8265434

TA贡献1813条经验 获得超2个赞

要构建更复杂的查询,还可以选择使用内置的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 it

q_objects = Q()


# loop trough the list and create an OR condition for each item

for item in list:

    q_objects.add(Q(pk=item), Q.OR)

    # for our list_with_strings we can do the following

    # 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


查看完整回答
反对 回复 2019-09-19
  • 3 回答
  • 0 关注
  • 821 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信