Reputation: 301
I'm beginning with Django and I would like to know how I can get attributs from my Django queryset.
I have this queryset :
get_country = Download.objects.filter(pub__publication__id=pubsd.id).values('country__name').order_by('country__name').annotate(count_country=Count('country__name'))
It returns :
<QuerySet [{'country__name': 'France', 'count_country': 1}, {'country__name': 'Germany', 'count_country': 2}]>
So I would like to display in my template the country name with the highest count_country
I would like to know how I can do that ?
Thank you so much
Upvotes: 1
Views: 186
Reputation: 27513
in view
return render(request,'template.html','{'country':'get_country'}
in template
{% for key, values in country.items %}
<tr>
<td>{{key}}</td>
<td>{{values }}</td>
</tr>
{% endfor %}
get_country = Download.objects.filter(pub__publication__id=pubsd.id).values('country__name').order_by('country__name').annotate(count_country=Count('country__name')).order_by('-count_country')
Upvotes: 1
Reputation: 476699
I think you better query this the reverse way, like:
max_country = Country.objects.filter(
download__pub__publication__id=pubsd.id
).annotate(
ndown=Count('download')
).order_by('-ndown').first()
(with download
here the related_name
of the Country
to Download
relation).
This will give you the Country
object with the most related Download
s, you can then do processing or rendering on the Country
object, like you can do with any Country
object.
If you for example pass the object to the template, you can render it like:
Most downloads are from {{ max_country.name }}
Upvotes: 1