[Fixed]-Django models sum of classes fiels

1👍

Based on what you wrote, you could get the value of a single Stage as (with stage_instance being your Stage instance):

ZoneSubStage.objects.filter(substage__stage=stage_instance).aggregate(Sum('value'))
# This will return {'value__sum': 90}

If you want to get the value by calling stage_instance.value, the easiest way would be to add value property method to Stage model.

class Stage(models.Model):
    stage_number = models.CharField()
    stage_name = models.CharField()
    zones = models.ManyToManyField(Zone, through='ZoneStage')

    @property
    def value(self):
        return ZoneSubStage.objects.filter(substage__stage=self).aggregate(Sum('value')).get('value__sum', 0)

Leave a comment