I have:
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
I need: the sum of x for every plant. What I tried in my view is this but it does not. I get the 'Recording' object has no attribute 'aggregate'
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')))
But I get the 'Recording' object has no attribute 'aggregate'
You can only apply aggregations to things that are database fields. x as have it define is a method on the model.
Recording.objects.values("plant").annotate(
agg=Sum(F("no_recording")*F("plant__multiplier"),
output_field=FloatField())
)
which should group by plant id the annotate the queryset with the sum of no_recording * plant__multplier
See: https://docs.djangoproject.com/en/1.11/topics/db/aggregation/#cheat-sheet