2016-08-04 108 views
1

我是新的django,想知道是否有一種更有效的方式來過濾除條件語句外。基於局部變量的Django條件過濾器

考慮:

test_names = ["all"] 
test_types = ["a", "b", "c"] 
... (more lists) 

我知道我能做到這一點:

q = tests.objects.all() 

if test_names[0] == "all": 
    q = q.all() 
else: 
    q = q.filter("name__in=test_names") 

if test_types[0] == "all": 
    q = q.all() 
else: 
    q = q.filter("type__in=test_type") 

etc... 

我想是這樣的:

q = test.objects \ 
     .filter((if test_names[0]=="all") "name__in=test_names") \ 
     .filter((if test_types[0]=="all") "type__in=test_types") \ 
     ...etc 

我想避免的if語句,因爲我必須在基於不同列表(例如「test_names」)的相同查詢數據上多次執行此操作。

回答

0

您在列表中有條件,因此您需要if以確保不同條件。你也許能夠逃脫一個查詢語句,但您需要在您的名單工作:

test_name_filter = {} if test_names[0] == 'all' else {'name__in': test_names} 
test_type_filter = {} if test_type[0] == 'all' else {'type__in': test_types} 
# ...... 
q = test.objects.filter(**test_name_filter).filter(**test_type_filter) 

這應該工作,因爲:

  1. Django的ORM過濾器可以接受的篩選條件的字典,鍵作爲標準和值作爲過濾器值。

  2. 空字典就像不過濾任何東西,意味着返回一切。