Mr T.
Mr T.

Reputation: 4498

django - aggregate data according to field in model


I have a model with a CharField with choices. I want to aggregate the model and get a list of all of the choices and the number of models in each choice. So if i have:

model1: a
model2: b
model3: c
model4: a
model5: c
model6: c

I want to build a django query set to get the following result (in json if i can)

{a: 2, b: 1, c: 3}

Is this even possible with the django orm or do i need to run a pure sql query?
Thanks.

Upvotes: 0

Views: 387

Answers (1)

user2390182
user2390182

Reputation: 73460

This should give you the dict you are looking for. Be careful, however, with the order of annotate and values:

from django.db.models import Count

d = {
    x['field_name']: x['count'] 
        for x in model.objects
            .annotate(count=Count('field_name'))  
            .values('field_name', 'count')
            .distinct()
}

If you want to convert this to json use the json module:

import json

json_string = json.dumps(d)

Upvotes: 1

Related Questions