Django count Items in QuerySet


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.


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.


Model: RateLimitRequests

requests_for_rate_limit = RateLimitRequests
.filter(ip="", 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
.filter(ip="", unit="h", value="11")

no_requests_for_rate_limit contains now the number of entries.


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.




Leave a Reply