Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

130
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

0

Try this

Sales.objects.all().extra(select={
            'total': 'Sum(price * count - cost)'
        }).values("total")
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda