2016-08-04 83 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. 空字典就像不过滤任何东西,意味着返回一切。