简体   繁体   中英

Django - Annotating the sum of a certain field in One To Many model

I am trying to get the sum of revenue of all the sales project, but I am not sure how to do it.

Here are my models.py (simplified version but kept all the neccessary parts)

class Quotation(models.Model):

    decisions = (
        ('approved', 'Approved'),
        ('rejected', 'Rejected'),
        ('pending', 'Pending'),
    )

    quotation_id = models.AutoField(primary_key=True)
    salesProject = models.ForeignKey('SalesProject' ,related_name='quotations', on_delete=models.CASCADE)
    quotation = models.MoneyField(max_digits=10, decimal_places=2)
    decision = models.CharField(max_length = 20, choices = decisions, default='pending')

class SalesProject(models.Model):

    sales_project_id = models.AutoField(primary_key=True)
    sales_project_name = models.CharField(max_length=100)
    sales_project_est_rev  = MoneyField(max_digits=10, decimal_places=2)

What I want to do is to get the sum of all the 'quotation' field under the Quotation model that is tied to the same SalesProject instance. Is there a way to do so?

My ideal output would be something like this (where actual_revenue is the sum of all the quotations tied to that particular SalesProject)

[{ sales_project_id: 1, sales_project_name: 'Test Project', sales_project_est_rev: 200000, actual_revenue: 150000}, {...}, ...]

All help is appreciated, thanks all!

Use sum function from django.db.models and annotate

from django.db.models import Sum
SalesProject.objects.annotate(actual_revenue=Sum('quotation__quotation'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM