Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

252
Views
Python nested loop calculate sum

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'

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!