如何使用 Django ORM 在特定 fiscal_year 的会话中获取 production_volume 的总和

How to get sum of the production_volume in a seasion of a particular fiscal_year using Django ORM

在这里,我试图获得 production_volume 个不同季节的总和,特别是 production_year: 这是我的模型:


class FiscalYear(BaseModel, models.Model):
    year = models.CharField(max_length=256)

class Season(BaseModel, models.Model):
    name = models.CharField(max_length=256)    
    season_month = models.ManyToManyField(Month)

class Product(BaseModel, models.Model):
    name = models.CharField(max_length=256)
    category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.SET_NULL, related_name='product_category')
    description = models.CharField(max_length=1000)
    hs_code = models.CharField(max_length=256, unique=True)
    photo = models.ImageField(upload_to='media/product/%Y/%M/', null=True, blank=True)
    production_unit = models.ForeignKey(MeasurementUnit, related_name='product_unit', null=True, blank=True, on_delete=models.SET_NULL)


class Production(BaseModel, models.Model):
    product = models.ForeignKey(Product, related_name='production_product', on_delete=models.CASCADE)
    district = models.ForeignKey(DistrictLevel, related_name='production_district', on_delete=models.CASCADE)
    production_volume = models.FloatField()
    production_year = models.ForeignKey(FiscalYear, related_name='production_year', null=True, blank=True, on_delete=models.SET_NULL)
    seasons = models.ManyToManyField(Season, related_name='product_season')

我通过使用 for loop, aggregate 得到结果,但我认为这不合适。下面是:

        fiscal_year = FiscalYear.objects.all().first() # for test
        for i in Season.objects.all():
            production_year = Production.objects.filter(production_year = fiscal_year).filter(seasons=i).aggregate(total_production = Sum('production_volume'))
            print(production_year ,909090)

如何通过 ORM 方法获得结果。 我尝试将 related_name 与 aggregate 和 annotate 一起使用,但它没有用。下面是我想要的:

这有帮助吗?

production_year = Production.objects.filter(production_year = fiscal_year).values('seasons').annotate(total_production = Sum('production_volume'))