Search code examples
djangoannotations

Django annotate: sum all records by asset | only one table


My django model:

class Movimentacao(models.Model):
    product = models.CharField(max_length=300)
    value = models.DecimalField(max_digits=19, decimal_places=2)

I'm trying to SUM all value by product using django annotate. I tried:

query = Movimentacao.objects.annotate(total=Sum('value')
                                    ).values('product', 'total'
                                    ).order_by('product')

There are a lot of repeated products (multiple lines) with different values and I'd like to group all same products and sum their respective values.

But it's showing all records without grouping and summing all of them.

I wouldn't like to use aggregate in this case.

Tks


Solution

  • You use .values(…) [Django-doc] first:

    from django.db.models import Sum
    
    query = (
        Movimentacao.objects.values('product')
        .annotate(total=Sum('value'))
        .order_by('product')
    )

    That being said, if the same product occurs multiple times, it is normally best practice to make a Product model and work with a ForeignKey.