Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

253
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda