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?

4

1 に答える 1

4

クエリtop_clientsを実行しているので、w/から開始することをお勧めしClientます。

top_clients = Client.objects.annotate(total_business=Sum('order__grand_total')).order_by('-total_business')

次にテンプレートで

{% for c in top_clients %}
<li>{{ c.total_business|currency }} {{ c.company_name }}</li>
{% endfor %}
于 2012-06-09T07:19:28.923 に答える