Reputation: 55
I have a django model and each entry in the table has a type ID. I need to get a count for each type.
Given this line in the documentation:
A count() call performs a SELECT COUNT(*) behind the scenes, so you should always use count() rather than loading all of the record into Python objects and calling len() on the result
Is it more efficient to get every object and count each type programmatically or do a database .count() for each type? I am using a postgresql database.
Upvotes: 0
Views: 93
Reputation: 55448
Use aggregation, e.g. MyModel.objects.values('type_id').annotate(Count('type_id'))
This does a sensible query, not something that's going to "get every object and count each type" which would be way too much work!
More about this here https://docs.djangoproject.com/en/1.8/topics/db/aggregation/#cheat-sheet
Upvotes: 4