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

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

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