在这里,我试图获得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循环,聚合得到了结果,但我认为这是不合适的。如下所示:
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一起使用,但不起作用。下面是我想要的:

发布于 2021-05-08 01:03:31
这有帮助吗?
production_year = Production.objects.filter(production_year = fiscal_year).values('seasons').annotate(total_production = Sum('production_volume'))https://stackoverflow.com/questions/67438771
复制相似问题