python - Django 注释与 select_related

标签 python django

我的应用程序中有一个名为“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/

相关文章:

python - Django - 使用 ManyToMany 保存表单集

python - 你是否很难用 Python 保持 80 列?

python - 如何使用 Python SDK 连接 couchbase 集群?

python - 通过 Python 版本制作 `nosetests` 脚本选择文件夹

python - blender 和 conda

python - 无法在本地主机上的 Django VirtualEnv 中访问 MySQL 数据库

django - Redis 告诉我 "Failed opening .rdb for saving: Permission denied"

python - 在 DjangoModelFactory 中使用 Django faker 创建的克隆模型字段

javascript - 为什么 angularJS 中的 $http.delete 不起作用?

python - 安装适用于 Python 的 MySql 连接器时出现问题