Count vs len on a Django QuerySet

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

    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.

提交回复
热议问题