2017-11-11 138 views
1

我有查詢集的列表(全部爲同一型號):Django的合併多個查詢集(同一型號)

results = Entry.objects.all() 
result_elms = [] 
if city_list: 
    for city in city_list: 
    result_elms.append(results.filter(address__city__icontains=city)) 

if county_list: 
    for county in county_list: 
     results_elms.append(results.filter(address__county__icontains=county)) 
#other filters here, daynamically created 

#how can I combine all results_elms (querysets) into one? 

我知道,我可以使用|運營商查詢集從相同的模型結合起來。 但是我怎樣才能將它應用於result_elms列表中的所有元素?

+0

你的問題沒有足夠的細節給出答案。您應該爲其他人提供足夠的信息來重現問題,並且明確描述您正在查找的結果(也不需要「if」語句)。 – thebjorn

+0

你用'__in'試過了嗎?這應該對你有所幫助。查看更多[here](https://docs.djangoproject.com/en/1.11/topics/db/queries/#the-pk-lookup-shortcut) – aquaman

+0

@thebjorn你是什麼意思?我確切的問題是我如何申請| (結合oparator)列表中的所有查詢集。我應該提供哪些其他信息? – dease

回答

3

您可以使用Q對象:

from django.db.models import Q 

results = Entry.objects.all() 
q = Q() 
for city in city_list: 
    q = q | Q(address__city__icontains=city) 
results.filter(q) 

文檔(https://docs.djangoproject.com/en/1.7/topics/db/queries/#complex-lookups-with-q)有更多的細節和例子。

+0

這是我所需要的,謝謝:-) – dease

+0

額外信息的一點點清楚你需要什麼 - 高興地幫助:-) – thebjorn

+0

爲什麼'q = Q()'然後'q = q | Q(address__city__icontains =城市)'? – ammarx

-1

如果您至少使用Django 1.11,這是一個單行。

final_results = result_elms[0].union(*result_elms[1:]) 

這裏是鏈接到documentaion。有關更多示例,請參閱我的blog post