Django 在模板中获取聚合
我有这个Django模型:Django 在模板中获取聚合,django,Django,我有这个Django模型: class Location(models.Model): name = models.CharField(primary_key=True, max_length=100) customer = models.OneToOneField(Customer, default=None) class Customer(models.Model): name = models.CharField(primary_key=True, max_len
class Location(models.Model):
name = models.CharField(primary_key=True, max_length=100)
customer = models.OneToOneField(Customer, default=None)
class Customer(models.Model):
name = models.CharField(primary_key=True, max_length=100)
class Order(models.Model):
amount = models.PositiveIntegerField(default=0)
customer = models.ForeignKey(Customer, default=0)
在我看来,我是这样理解的:
locations = models.Location.objects.all()
{% for location in locations %}
{{ location.customer.name }}
{% endfor %}
{% for customer in customers %}
{{ customer.name }} ordered {{ customer.orders_count }} items
{% endfor %}
模板中的列表如下所示:
locations = models.Location.objects.all()
{% for location in locations %}
{{ location.customer.name }}
{% endfor %}
{% for customer in customers %}
{{ customer.name }} ordered {{ customer.orders_count }} items
{% endfor %}
我想添加与该客户连接的所有订单的所有金额的总和,例如:
{% for location in locations %}
{{ location.customer.name }} ordered {{ location.customer.orders.sum(amount) }} items
{% endfor %}
根据,我应该在视图中这样做,但是如何做呢?您应该使用.annotate
():
然后在模板中,您可以这样使用它:
locations = models.Location.objects.all()
{% for location in locations %}
{{ location.customer.name }}
{% endfor %}
{% for customer in customers %}
{{ customer.name }} ordered {{ customer.orders_count }} items
{% endfor %}
经过一番周旋后,我发现这是可行的:
locations = models.Location.objects.annotate(num_order=Count('customer__order'))
然后在模板中使用:
{% for location in locations %}
{{ location.customer.name }} ordered {{ location.num_order }} items
{% endfor %}
呃,按照这个,?你到底哪里有问题?@DanielRoseman我用我尝试过的方法更新了这个问题,问题在于我有另一个模型(我之前发布了错误的模型)。我让它工作了。有没有办法过滤出一些订单
s?@BartFriederichs请举例说明您想要什么我只想计算具有特定状态的订单。@BartFriederichs可能您可以使用@BartFriederichs查看