Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Group Counts on Foreign Keys

Tags:

python

sql

django

I am new to Django, transitioning from PHP. I have the below query to list the top ten counts of a grouping variable which is a foreign key to another table.

Model.objects.values('group').annotate(count = Count('group')).order_by('-count')[:10]

The data is destined for a template, detailing the 'league'. When printing to the template, I would like to list the readable name of the group as opposed to the integer foreign key value. Using values() in a query returns a dictionary rather than an object an previous methods I have used for handling foreign keys have failed. Thanks in advance!

like image 453
Simon Avatar asked Jun 07 '26 17:06

Simon


1 Answers

Using the values() queryset function, you can pull the fields of a foreign key model by using:

.values('foreign__field')

Referring to your example, and assuming your Group model has a "name" field, you can use:

Model.objects.values('group', 'group__name')...

If you pass that dict into the template, then you can refer to the 'group__name' key:

{% for g in groups %} {{ g.group__name }}

like image 159
pcoronel Avatar answered Jun 10 '26 07:06

pcoronel