Django single query to count & use data on for loop?

Viewed 344

I need to display total count & also use the queryset to loop on the template ! But the thing is its causing two queries to do this, is there any efficient way to manage this on single query ?

data = Data.objects.filter(pk=pk)
count = data.count // 1st query

and then using data to iterate over loop on template // this makes second query 

Is there any other best way to do the same thing or it needs these two queries for sure ?

1 Answers

You can use len on the queryset to force the evaluation and at the same time be able to get the count. This will prevent hitting the database again when you iterate through the same queryset:

data = Data.objects.filter(pk=pk)
#  Hits the db and evaluates data
count = len(data) 

#  Will not hit the db again
for d in data: 
    print(d)

This should end up with just one query.

Related