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"...
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.
Try this
Sales.objects.all().extra(select={
'total': 'Sum(price * count - cost)'
}).values("total")