Count vs len on a Django QuerySet

前端 未结 5 1068
栀梦
栀梦 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:38

    Summarizing what others have already answered:

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

    It is also true that if after this operation, the whole queryset will be iterated, then as as whole it could be slightly more efficient to use len().

    However

    In some cases, for instance when having memory limitations, it could be convenient (when posible) to split the operation performed over the records. That can be achieved using django pagination.

    Then, using count() would be the choice and you could avoid to have to fetch the entire queryset at once.

提交回复
热议问题