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.)
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.
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.
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.
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.
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'sSELECT COUNT(*)
, and Django provides acount()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With