Is there a downside to using “.filter().filter().filter()…” in Django?

断了今生、忘了曾经 提交于 2019-12-08 22:00:56

问题


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.


回答1:


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 ANDed 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)



回答2:


In addition to Manoj's answer, here's how you can analyze the sql generated for a QuerySet object:

result1 = SomeModel.objects.filter(field1=100, field2=200)
print "Result1", results1.query

result2 = SomeModel.objects.filter(field1=100).filter(field2=200)
print "Result2", result2.query


来源:https://stackoverflow.com/questions/3733324/is-there-a-downside-to-using-filter-filter-filter-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!