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

332
Visualizações
Django: Sum up Counts in one query

I have a list of elements that i would like to rank according to the count of related manytomany elements. I think aggregating the counts of those source elements is the right way, but i haven't found a solution yet.

class Element(models.Model):
     Source1 = models.ManyToManyField(Source1)
     Source2 = models.ManyToManyField(Source2)
     Source3 = models.ManyToManyField(Source3)


Ranked = (Element.objects.all().aggregate(
         Ranked=Sum(F('Source1') + F('Source2') + F('Source3'), output_field=IntegerField)['Ranked']
))
about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

One possible solution:

agg_data = Element.objects.aggregate(total_source1=Count('Source1'), total_source2=Count('Source2'), total_source3=Count('Source3'))
total_count = sum(agg_data.values()) # this is value which you need

Update: If you want to get list of Element:

res = Element.objects.all().annotate(total_source1=Count('Source1'), total_source2=Count('Source2'), total_source3=Count('Source3'))
.annotate(total_count=F('total_source1') + F('total_source2') + F('total_source3')).order_by('-total_count')
about 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