Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading