slothis · English

Django QuerySet Performance: count() vs len()

2020-12-05 · Updated: 2026-08-11 · Original (Korean)

This article was translated from the original Korean post with AI assistance. Read the original Korean post →
Official Django framework logo written in white lowercase letters on a dark green background

During a recent code review, I received a comment asking me to change my code to use count() instead of len() for getting the number of rows. As a total newbie to ORMs and Django, I dug through a few StackOverflow threads, and it turns out everyone recommends using count to check rows whenever possible. Let's find out why.

Let's say we want to check the current number of Users in my service.

(Be careful: if you do this just for fun in a system with millions or tens of millions of users, you'll get called in by the company's DevOps bros.)

qs = User.objects.all()

# You can use the queryset's count() method.
def user_count_by_count():
    return qs.count()

# Or you can check it with len().
def user_count_by_len():
    return len(qs)

In this case, with count(), SELECT COUNT(*) FROM User is executed in the RDBMS, and the count value is passed to Python.

With len(), SELECT * FROM User is executed once in the RDBMS, and the result passed to Python is counted using len().

People often say, "If you need to count the number of rows, use count()." The reason is that if you try to substitute count with len(), fetching takes O(N) time. Also, storing this result in the web server's memory causes O(N) in storage, and the time it takes to copy causes an additional O(N) in time. On top of that, there's the time it takes for len() itself to run. These two processes will vary depending on your infrastructure, but count is said to be about twice as fast.

However, there are times when using len() is more advantageous than count().

qs = User.objects.all()

def prefer_len_to_count():
    # Assuming there's a telephone field in the User info, we collect that info into a list.
    telephones = [p.telephone for p in qs]
    # Do some work with that info...
    ...
    # Get the number of items in qs (figure out the use case yourself)
    len(qs)

If you are fetching and using the queryset like the example above, len is slightly more advantageous. The reason is that count() would have to access the RDBMS twice (once for the fetch, once for count()).

I might get scolded by the DevOps bros for saying this, but unless you are counting an incredibly large number of rows (this standard varies wildly depending on your infrastructure), it's perfectly fine to just use count.

Naturally, using count is also recommended in templates.

The count below

{{ some_queryset.count }}

is more recommended than the len below.

{{ len(some_queryset) }}

Reference: stackoverflow.com/questions/14327036/count-vs-len-on-a-django-queryset


#django #Django