ChocoBomb
ChocoBomb

Reputation: 301

Django : Get the highest queryset attribute in my template

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

Answers (2)

Exprator
Exprator

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

willeM_ Van Onsem
willeM_ Van Onsem

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 Downloads, 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

Related Questions