Python嵌套循环计算总和

时间:2017-04-26 19:06:39

标签: python django django-views

我有:

models.py

class Plant(models.Model):
    plant_name = models.CharField()
    multiplier = no_recording = models.PositiveIntegerField(default=1)

class Recording(models.Model)
    plant = models.ForeignKey(Plant, on_delete=models.CASCADE)
    no_recording = models.PositiveIntegerField(default=1)

    def x(self):
        return self.no_recording*self.plant.multiplier

我需要:每株植物的x总和。我在我看来尝试的是这个,但事实并非如此。我得到了录音'对象没有属性'聚合'

views.py

def home(request):
    plants = Plant.objects.all()
    total_recording_per_plant = []
    for plant in plants
        for recording in plant.recording_set.all():
         total_recording_per_plant.append(recording.aggregate(sum=Sum('x'))) 

但是我得到了录音'对象没有属性'聚合'

1 个答案:

答案 0 :(得分:0)

您只能将聚合应用于数据库字段。它定义的x是模型上的方法。

Recording.objects.values("plant").annotate(
    agg=Sum(F("no_recording")*F("plant__multiplier"),
    output_field=FloatField())
)

应该按工厂ID分组,使用no_recording * plant__multplier的总和来注释查询集

请参阅:https://docs.djangoproject.com/en/1.11/topics/db/aggregation/#cheat-sheet