【发布时间】:2016-12-10 23:28:06
【问题描述】:
我是 django 新手,想知道除了 if 语句之外是否还有更有效的条件过滤方式。
给定:
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”)的相同查询数据执行多次。
【问题讨论】: