How to determine the count of distinct values in a Django model's field?
distinct, django, python
Solution
from django.db.models import Count
Profile.objects.values('age').annotate(Count('age'))
Result: [{'age': 10, 'age__count': 52}, ...]
Problem
Suppose I have the following model: ``` from django.db import models class Profile(models.Model): ''' Represents information about a user ''' # ... age = models.PositiveSmallIntegerField() ``` If I wish to determine each of the distinct ages present in the table, I can do this: ``` Profile.objects.distinct('age') ``` However, this doesn't include any information on the number of rows that contain each distinct age. Is there any way to obtain this information without resorting to raw SQL?