简体   繁体   English

如何通过 django 中的注释进行分组?

[英]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:我用 values().annotate() 或 aggregate() 尝试了一切,或者通过使用 Subquery 的教程,我无法得到我想要的,让我解释一下:

There is what I get with QuizzUserItem.objects.filter(examuser=user_exam).values('item__question', 'item')我得到了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__question 分组并得到这个结果:

{'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...但我没有 item_ids 762,763 ......

Thank you for reading感谢您阅读

You can work with the ArrayAgg aggregate [Django-doc] to obtain a list of items:您可以使用ArrayAgg聚合 [Django-doc]来获取项目列表:

from django.contrib.postgres.aggregates import ArrayAgg

QuizzUserItem.objects.filter(
    examuser=user_exam
).values(
    'item__question'
).annotate(
    items=ArrayAgg('item__question')
).order_by('item__question')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM