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」)的相同查詢數據上多次執行此操作。