Search code examples
pythondjangodjango-annotate

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


Solution

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