Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

255
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda