[Django]-Group django queryset by foreign key / related field

3👍

The most simple query you can make would be:

qs = Question.objects.annotate(answer_count = Count('answers')) \
            .filter(answer_count__gte=1).prefetch_related('answers')
# get answer list related to first question
print qs[0].answers.all()

assuming you’ve added related_name attribute:

class Answer(models.Model):
    question = models.ForeignKey(Question, related_name='answers')

I can’t imagine a use case of getting all the questions from the database, you typically paginate the data or something, so the slow queries should not be an issue.

Leave a comment