Count vs len on a Django QuerySet

前端 未结 5 1061
栀梦
栀梦 2020-12-04 11:13

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

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-04 11:23

    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.

提交回复
热议问题