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

252
Vistas
how to group by with annotate in django?

I tried absolutely everything with values().annotate() or aggregate() , or by following tutorials with Subquery I cant get what I want, let me explain :

There is what I get with QuizzUserItem.objects.filter(examuser=user_exam).values('item__question', 'item')

{'item': 759, 'item__question': 429}
{'item': 762, 'item__question': 430}
{'item': 763, 'item__question': 430}
{'item': 767, 'item__question': 431}

What I want is to group by item__question and get this result :

{'item': 759, 'item__question': 429}
{'item': 762,763 'item__question': 430}
{'item': 767, 'item__question': 431}

I start to think there is absolutely no way :/


What I tried :

QuizzUserItem.objects.filter(examuser=user_exam).values('item__question','item').annotate(items_number=Count('item__question'))

I got :

{'item': 759, 'item__question': 429, 'items_number': 1}
{'item': 762, 'item__question': 430, 'items_number': 1}
{'item': 763, 'item__question': 430, 'items_number': 1}
{'item': 767, 'item__question': 431, 'items_number': 1}

or

QuizzUserItem.objects.filter(examuser=user_exam).values('item__question').annotate(items_number=Count('item__question'))

This one is the closest result that I got :

{'item__question': 429, 'items_number': 1}
{'item__question': 430, 'items_number': 2}
{'item__question': 431, 'items_number': 1}

But I have not the item_ids 762,763...

Thank you for reading

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

You can work with the ArrayAgg aggregate [Django-doc] to obtain a list of items:

from django.contrib.postgres.aggregates import ArrayAgg

QuizzUserItem.objects.filter(
    examuser=user_exam
).values(
    'item__question'
).annotate(
    items=ArrayAgg('item')
).order_by('item__question')
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