0

Lets say I have a django model table

class Table(models.Model):
      name         = models.CharField()
      date_created = models.DatetimeField()
      total_sales  = models.DecimalField()

some data for context

Name date-created total-sales
a 2020-01-01 200
b 2020-02-01 300
c 2020-04-01 400
* ********** ***
c 2020-12-01 1000
c 2020-12-12 500

now I want to filter an aggregate of

total_yearly_sales = 10500

current month being December

total_monthly_sales = 1500

daily_sales

total_daily_sales = 500

also do a Group by by name

models.Table.objects.values('Name').annotate(Sum('total-sales')).order_by()

I want to do this in one query(one db hit)

Hence the query should generate

  1. total_yearly_sales
  2. total_monthly_sales
  3. total_daily_sales
  4. total_sales_grouped_by_name ie {a:200, b:300, c:1900}

I know this is too much to ask. Hence let me express my immense gratitude and thanks for having a look at this.

cheers

The above queries I can generate them individually like so

today = timezone.now().date()
todays_sales = models.Table.filter(date_created__date__gte=today, date_created___date__lte=today).aggregate(Sum('total_sales'))

=> 500
monthly_sales(this month) = models.Table.objects.filter(date_created__year=today.year, date_created__month=today.month).aggregate(Sum('total_sales'))
 =>10500
total_yearly_sales = models.Table.objects.filter(date_created__year=today.year).aggregate(Sum('total_sales')) => 10500
Futs TV
  • 1
  • 1

0 Answers0