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:
- Give a related name to customer in Order model:
customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name=“orders”)
- Get orders count:
Customer.objects.get(id=1).orders.count()
Or access this attribute in template something like:
{{ customer.orders.count }}
- 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”))
- [Django]-Django WSGIRequest.get_full_path() doesn't return the full URI
- [Django]-Where is Django base.html file? Add additional static style sheet
- [Django]-Display mpld3 chart in HTML with django
- [Django]-Django check if superuser in class-based view
- [Django]-Auto Update Django Model based on other model fields
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”))
- [Django]-Calculate average exchange rate for time period
- [Django]-Authentication failed: [Errno 1] _ssl.c:510: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
- [Django]-Getting Module parse failed: Unexpected token (1:0) error when I try to import css file for a specific component in react
- [Django]-How do I quickly get a weighted random instance of a Django model instance based on a weight field on that model?