Do using queryset.count() caches the queryset?

I'm making some filtering in my endpoint, and one of the filters are only applied if the filtered queryset has more than 30 items.

yesterday_date = timezone.now() - timezone.timedelta(days=1)
if query_dict.get("active"):
    active_query = cleaned_query.filter(created_at__gt=yesterday_date)
    if active_query.count() > 30:
        cleaned_query = active_query
    else:
        cleaned_query = cleaned_query[:30]

My doubt is, will the .count() method already evaluates and caches the queryset or should I use len(queryset) to avoid another database hit in case it's bigger than 30?

If you check django's docs about When Querysets Are Evaluated

You'll see some information about counting...

Note: If you only need to determine the number of records in the set (and don’t need the actual objects), it’s much more efficient to handle a count at the database level using SQL’s SELECT COUNT(*). Django provides a count() method for precisely this reason.

So a count() doesn't evaluate the set, whereas a len() does.

Back to Top