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
For people who prefer test measurements(Postresql):
If we have a simple Person model and 1000 instances of it:
class Person(models.Model):
name = models.CharField(max_length=100)
age = models.SmallIntegerField()
def __str__(self):
return self.name
In average case it gives:
In [1]: persons = Person.objects.all()
In [2]: %timeit len(persons)
325 ns ± 3.09 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [3]: %timeit persons.count()
170 ns ± 0.572 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
So how can you see count()
almost 2x faster than len()
in this particular test case.