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
Source:stackexchange.com