【问题标题】:Django conditional filter based on local variable基于局部变量的Django条件过滤器
【发布时间】: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”)的相同查询数据执行多次。

【问题讨论】:

    标签: python django filter


    【解决方案1】:

    您的列表中有条件,因此对于不同的条件,您肯定需要ifs。您也许可以使用一个查询语句,但您需要处理您的列表:

    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 过滤器可以接受过滤条件作为 dict,键作为条件,值作为过滤器值。

    2. 空字典就像不过滤任何东西,意味着返回所有东西。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-13
      • 1970-01-01
      • 1970-01-01
      • 2016-08-15
      • 2010-10-22
      • 1970-01-01
      相关资源
      最近更新 更多