Django count Items in QuerySet

Problem

You´re new to Django and need to count the number of items in your QuerySet (for a query), e.g. to check that the current request didn´t go over the rate limit you allowed.

Solution

Create your QuerySet by querying the Model as you are used to. Then simply append a .count() to your chain and you receive the number.

E.g.:

Model: RateLimitRequests

requests_for_rate_limit = RateLimitRequests
.objects
.filter(ip="127.0.0.1", unit="h", value="11") 

requests_for_rate_limit is now a QuerySet and will contain all requests for the parameters

no_requests_for_rate_limit = RateLimitRequests
.objects
.filter(ip="127.0.0.1", unit="h", value="11")
.count()

no_requests_for_rate_limit contains now the number of entries.

Explanation

While applying the normal filter you request from the database that it should return all matching entries (with all data). That can take quite a while and uses up resources unnecessarily.

By appending the .count() you tell the database to use the SQL COUNT function and return it´s result. Instead of all the data of all entries that match your query.

So in short:

By using .count() you save resources, don´t have to worry about data format and leverage the available optimizations on your database to quickly retrieve the number of entries you require.

Let me know when this helped you.

Best,

Frank

Sources:

https://stackoverflow.com/questions/11377856/how-to-count-number-of-items-in-queryset-without-count

https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.count

Leave a Reply