我是 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”)对相同的查询数据执行多次此操作。
最佳答案
您的列表中有条件,因此您肯定需要针对不同条件的 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)
这应该有效,因为:
Django ORM 过滤器可以接受过滤条件作为字典,键作为条件,值作为过滤值。
空字典就像不过滤任何东西,意味着返回所有内容。
关于python - 基于局部变量的Django条件过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38774133/