亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在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 關注
  • 898 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號