第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

如何在Django中動(dòng)態(tài)組合OR查詢過濾器?

如何在Django中動(dòng)態(tài)組合OR查詢過濾器?

jeck貓 2019-09-19 15:25:17
從示例中,您可以看到多個(gè)OR查詢過濾器:Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3))例如,這會(huì)導(dǎo)致:[<Article: Hello>, <Article: Goodbye>, <Article: Hello and goodbye>]但是,我想從列表中創(chuàng)建此查詢過濾器。怎么做?例如 [1, 2, 3] -> Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3))
查看完整描述

3 回答

?
HUX布斯

TA貢獻(xiàn)1876條經(jīng)驗(yàn) 獲得超6個(gè)贊

您可以按如下方式鏈接查詢:


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)


查看完整回答
反對(duì) 回復(fù) 2019-09-19
?
慕姐8265434

TA貢獻(xiàn)1813條經(jīng)驗(yàn) 獲得超2個(gè)贊

要構(gòu)建更復(fù)雜的查詢,還可以選擇使用內(nèi)置的Q()對(duì)象的常量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


查看完整回答
反對(duì) 回復(fù) 2019-09-19
  • 3 回答
  • 0 關(guān)注
  • 905 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)