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!
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 }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With