[Fixed]-Django – aggregate data according to field in model

1πŸ‘

βœ…

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)
πŸ‘€user2390182

Leave a comment