Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

129
Views
Error sum in sql request

I have model:

class Sales(ModelWithCreator, models.Model):
    date = models.DateField(default=datetime.date.today)
    merchandise = models.ForeignKey(Merchandise)
    partner = models.ForeignKey(Partner)
    count = models.PositiveIntegerField()
    debt = models.PositiveIntegerField(default=0)
    price = models.PositiveIntegerField()
    cost = models.PositiveIntegerField()

I have to get sum of all objects that model. I tried that:

Sales.objects.all().extra(select={
            'total': 'Sum(price * count - cost)'
        })

But, I got error:

column "sales_sales.id" must appear in the GROUP BY clause or be used in an aggregate function LINE 1: SELECT (Sum(price * count - cost)) AS "total", "sales_sales"...

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

I think you might want to use the .aggregate() function. See the Django documentation for Aggregation.

Something like this (though I haven't tested it):

Sales.objects.all().aggregate( total = Sum((F(price)*F(count)) - F(cost)) )

Also, that same documentation suggests using the .query() function to see what the resulting query is. That might help you see what is going wrong.

over 4 years ago · Santiago Trujillo Report

0

Try this

Sales.objects.all().extra(select={
            'total': 'Sum(price * count - cost)'
        }).values("total")
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!