使用“.filter()。filter()。filter()...”是否有缺点。在Django? [英] Is there a downside to using ".filter().filter().filter()..." in Django?
问题描述
链接多个呼叫
Model.objects \
.filter(arg1 = foo)\
.filter(arg2 = bar)\
...
将所有参数合并在一起:
Model.objects \
.filter(arg1 = foo,arg2 = bar)
我希望代码是可读的(有更多的过滤器调用比我显示的),但只有当没有牺牲性能。
更新:
忽略这个答案。看到更好的,正确答案。
感谢 @Sam 的头衔。
旧答案:
将以下两个调用解析为等效的SQL在Django中查询?
简短答案:是的。他们将生成等效的查询。
我用我正在使用的模型进行了验证。产生的查询在功能上是相同的。不同的过滤器
条件是在查询中一起编辑 AND
。
我希望代码是可读的(有更多的过滤器调用比我已经显示),但只有没有牺牲
实现可读性的一种方法是使用字典来收集所有过滤条件。例如
conditions = dict(arg1 = foo,arg2 = bar,....)
conditions.update (argN = baz)
Model.objects.filter(**条件)
Are the following two calls resolved to the equivalent SQL query in Django?
Chaining multiple calls
Model.objects \
.filter(arg1=foo) \
.filter(arg2=bar) \
...
Wrapping all the args together:
Model.objects \
.filter(arg1=foo, arg2=bar)
I'd like code to be readable (there are MANY more filter calls than I've shown), but only if there's no sacrifice to performance.
Update:
Disregard this answer. See this better, correct answer. Thanks @Sam for the heads up.
Old Answer:
Are the following two calls resolved to the equivalent SQL query in Django?
Short answer: yes. They will generate equivalent queries.
I verified this with a model I am using. the queries produced are functionally identical. The different filter
conditions are AND
ed together in the query.
I'd like code to be readable (there are MANY more filter calls than I've shown), but only if there's no sacrifice to performance.
One way to achieve readability is to use a dictionary for collecting all filter conditions. For e.g.
conditions = dict(arg1 = foo, arg2 = bar, ....)
conditions.update(argN = baz)
Model.objects.filter(**conditions)
这篇关于使用“.filter()。filter()。filter()...”是否有缺点。在Django?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!