I have a model in my app called "Orders" that has a foreign key relationship to another model called "Clients", the field is called "client".
I'm trying to do an annotate query to sum up a field in the database to figure out which client has purchased the most, while also including the related data from the "Clients" table. Here is what i've come up with so far:
top_clients = Order.objects.values('client_id').annotate(total_business=Sum('grand_total')).order_by('-total_business').select_related('client')
In my template I can easily access the "total_business" variable, but I cannot for some reason access the related "client" data.. here is my loop in the template;
{% for c in top_clients %}
<li>{{ c.total_business|currency }} {{ c.client.company_name }}</li>
{% endfor %}
Any idea why I cannot access the related data? Or is there a better way to do what I'm trying to do?
You are querying top_clients, thus better to start w/ Client:
top_clients = Client.objects.annotate(total_business=Sum('order__grand_total')).order_by('-total_business')
Then in template
{% for c in top_clients %}
<li>{{ c.total_business|currency }} {{ c.company_name }}</li>
{% endfor %}
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