Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django - show the length of a queryset in a template

Tags:

django

In my html file, how can I output the size of the queryset that I am using (for my debugging purposes)

I've tried

{{ len(some_queryset) }} 

but that didn't work. What is the format?

like image 950
bharal Avatar asked May 22 '12 03:05

bharal


People also ask

How do you find the length of a Queryset in Django?

Get length of queryset Django In such a case, you can use the count() method or the len() function to find the number of records in a queryset.

How do I find the size of a Queryset?

If the QuerySet only exists to count the amount of rows, use count(). If the QuerySet is used elsewhere, i.e. in a loop, use len() or |length. Using count() here would issue another SELECT-query to count the rows, while len() simply counts the amount of cached results in the QuerySet.

What is the difference between Len article objects all ()) and Article count ()?

len() will fetch all the records and iterate over them. count() will perform an SQL COUNT operation (much faster when dealing with big queryset).

What does Queryset []> mean?

A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.


2 Answers

Give {{ some_queryset.count }} a try.

This is better than using len (which could be invoked with {{ some_queryset.__len__ }}) because it optimizes the SQL generated in the background to only retrieve the number of records instead of the records themselves.

like image 114
Evan Grim Avatar answered Oct 18 '22 21:10

Evan Grim


some_queryset.count() or {{some_queryset.count}} in your template.

dont use len, it is much less efficient. The database should be doing that work. See the documentation about count().

However, taking buffer's advice into account, if you are planning to iterate over the records anyway, you might as well use len which will involve resolving the queryset and making the resulting rows resident in main memory - this wont go to waste because you will visit these rows anyway. It might actually be faster, depending on db connection latency, but you should always measure.

like image 21
Preet Kukreti Avatar answered Oct 18 '22 20:10

Preet Kukreti