In Django, do the following two snippets produce the same underlying SQL query?
qs = MyModel.objects.filter(group=1, type=2)
and
qs = MyModel.objects.filter(group=1).filter(type=2)
In Django, do the following two snippets produce the same underlying SQL query?
qs = MyModel.objects.filter(group=1, type=2)
and
qs = MyModel.objects.filter(group=1).filter(type=2)
Both are same and i even checked the sql query being generated.They are the same.
It depends actually, on whether there are joins or spanned lookups, especially through
M2M
relationship. For exampleYes
More on
QuerySet
sMore documentation on chaining
QuerySet
'sfilter
s: https://docs.djangoproject.com/en/dev/topics/db/queries/#chaining-filtersDifference between two mentioned calls
There is some difference, however. With every
filter()
method call you receive newQuerySet
object, so doing this call:seems to be wiser (in terms of performance and amount of code you need to write) than doing this call:
QuerySet
s are lazyAs in the title of this section, just getting
QuerySet
in return does not mean the query has been executed on the database. It is just a container of the conditions that will be used to perform the query.Documentation says: