简体   繁体   中英

How do i use annotate to group the child models by the parent models?

I have 3 models. PeerReview Answer and Statement. A Peer review has many answers, Each answer belongs to a Statement (or question if you will)

What I want is to get all answers from all PeerReviews grouped by their statements. So the end result should be a dictionary where there key is a statement object, and the value is a list of all the answers for that particular statement. If you would print it out it would look something like this:

{Statement A : [answer, answer, answer], Statement B : [answer,answer,answer], Statement C : etc etc}

I know that for group by queries i should use the annotate() method but all the examples i find are about count and sum actions. How do i use annotate to get the above mentioned dictionary as a result?

Thank you

If I understand what you want, you need to use the reverse foreign key relationship.

statements = Statement.objects.prefetch_related('answer_set__peer_review')

If you need a dictionary, then this would do it:

mapping = {s: list(s.answer_set.all()) for s in statements}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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