Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine the count of distinct values in a Django model's field?

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?

like image 222
Nathan Osman Avatar asked Nov 01 '25 18:11

Nathan Osman


1 Answers

from django.db.models import Count

Profile.objects.values('age').annotate(Count('age'))

Result: [{'age': 10, 'age__count': 52}, ...]
like image 87
Nikita Avatar answered Nov 04 '25 09:11

Nikita