Reputation: 3161
I couldn't find a way to print out when Django is actually hitting the database from a QuerySet method, but according to the docs, my example below should unnecessarily perform two queries, or does it?
queryset = MyModel.objects.all()
#Slicing evaluates a query
queryset = queryset[5:10]
#Serializing should also evaluate a query
data = serializers.serialize('json', queryset, fields=('pk', 'name'))
Upvotes: 0
Views: 243
Reputation: 43300
The only way that this code would do more than one query would be if the serializer includes data about a related field then a further query may be done in order to retrieve results for the related model.
As noted by knbk in the comments,
Slicing an unevaluated QuerySet usually returns another unevaluated QuerySet, but Django will execute the database query if you use the “step” parameter of slice syntax, and will return a list. Slicing a QuerySet that has been evaluated also returns a list.
Since you're not using a step, the slicing isn't the operation that evaluates the query
Upvotes: 1