3

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?

1 Answer 1

4

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 %}
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for your reply i didn't realize you could annotate related tables :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.