Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading