我的应用程序中有一个名为“Orders”的模型,它与另一个名为“Clients”的模型具有外键关系,该字段称为“client”。
我正在尝试执行注释查询以汇总数据库中的字段以确定哪个客户购买最多,同时还包括“客户”表中的相关数据。这是我到目前为止的想法:
top_clients = Order.objects.values('client_id').annotate(total_business=Sum('grand_total')).order_by('-total_business').select_related('client')
在我的模板中,我可以轻松访问“total_business”变量,但由于某种原因我无法访问相关的“客户”数据。这是我在模板中的循环;
{% for c in top_clients %}
<li>{{ c.total_business|currency }} {{ c.client.company_name }}</li>
{% endfor %}
知道为什么我无法访问相关数据吗?还是有更好的方法来完成我想做的事情?
最佳答案
您正在查询 top_clients
,因此最好从 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 %}
关于python - Django 注释与 select_related,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10957354/