[Django]-Count & Sum of Order Values for each customer (through iteration) in Django

2đź‘Ť

âś…

Since you want a queryset of Customer instances make your query on the Customer model itself instead of on Order, next I believe you will not need to use distinct here since the customer instances should be considered unique. Hence, you can make a query like:

from django.db.models import Count, Sum


customers = Customer.objects.annotate(order_count=Count('order'), order_value_sum=Sum('order__value'))


for customer in customers:
    print(customer.name, customer.order_count, customer.order_value_sum)

0đź‘Ť

Kindly note im typing the solution from my phone without testing it but this is what i think:

  1. Give a related name to customer in Order model:

customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name=“orders”)

  1. Get orders count:

Customer.objects.get(id=1).orders.count()

Or access this attribute in template something like:

{{ customer.orders.count }}

  1. Get orders count values by city

From django.db.models import Count, Sum

Customer.objects.values(“city”).annotate(order_count=Count(“orders”)).annotate(totals=Sum(“value”))

👤Yousef Alm

0đź‘Ť

Add realted_name to Order customer field:

class Customer(models.Model):
    name = models.CharField(max_length = 100)
    city = models.CharField(max_length = 100)

class Order(models.Model):
    value = models.FloatField()
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='orders')
 

query:

Customer.objects.values(“city”).annotate(order_count=Count(“orders”)).annotate(totals=Sum(“orders__value”))
👤Siva Sankar

Leave a comment