skip to Main Content

models.py

name = models.ForeignKey(CustomUser)
date = models.DateTimeField()
orders = models.IntegerField(default=0)

this is the model which counts daily orders of a user. the order which is made in the same day will just increase the orders count by one.

So how to make a query or serializer which gives the result of users with their total orders of all time

eg:

 [{name:albert, orders:35},
{name:Vncent, orders:35},
{name:john, orders:35},
{name:dion, orders:35},
{name:aoidi, orders:35},]

2

Answers


  1. from django.db.models import Count,Sum
    

    if you want total sum of orders you can use this:

    Shop.objects.values("date__date","name").annotate(daily_count=Sum("orders"))
    

    or if you want +1 for every instance of Model for the same date:

    Shop.objects.values("date__date", "name").annotate(daily_count=Count("orders"))
    

    Update:
    This will return counts as per Days instead total. You can remove date__date from values if you want all the counts without datetime filter as per @BairavanD’s answer.

    Login or Signup to reply.
  2. Try this code. It’ll actually group by the name and sum the orders. the total column name will be total_orders. I assume that your model is Customer

    from django.db.models import Sum
    
    customers = Customer.objects.values('name').annotate(total_orders=Sum('orders'))
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search