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

293
Vistas
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']
))
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

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')
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