Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count vs len on a Django QuerySet

In Django, given that I have a QuerySet that I am going to iterate over and print the results of, what is the best option for counting the objects? len(qs) or qs.count()?

(Also given that counting the objects in the same iteration is not an option.)

like image 990
antonagestam Avatar asked Jan 14 '13 21:01

antonagestam


People also ask

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

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.

How do you use LEN in Django?

To simply check the length of a string in Django, you can use the len() function. This function takes a string input and returns an integer value i.e. the length of a string. You can use the len function as shown below in the below example. I am executing the code in the Django shell.

What is count in Django?

Use Django's count() QuerySet method — simply append count() to the end of the appropriate QuerySet. Generate an aggregate over the QuerySet — Aggregation is when you "retrieve values that are derived by summarizing or aggregating a collection of objects." Ref: Django Aggregation Documentation.

How does Django count data?

You can either use Python's len() or use the count() method on any queryset depending on your requirements. Also note, using len() will evaluate the queryset so it's always feasible to use the provided count() method. You should also go through the QuerySet API Documentation for more information.


1 Answers

Although the Django docs recommend using count rather than len:

Note: Don't use len() on QuerySets if all you want to do is determine the number of records in the set. It's much more efficient to handle a count at the database level, using SQL's SELECT COUNT(*), and Django provides a count() method for precisely this reason.

Since you are iterating this QuerySet anyway, the result will be cached (unless you are using iterator), and so it will be preferable to use len, since this avoids hitting the database again, and also the possibly of retrieving a different number of results!).
If you are using iterator, then I would suggest including a counting variable as you iterate through (rather than using count) for the same reasons.

like image 183
Andy Hayden Avatar answered Oct 01 '22 17:10

Andy Hayden