mkay
mkay

Reputation: 33

Django GROUP BY ForeignKey query

This is my models.py:

class QuestionCategory(models.Model):
    name = models.CharField(max_length=200)

class Question(models.Model):
    question = models.CharField(max_length=200)
    answer = models.TextField()
    category = models.ForeignKey(QuestionCategory)

What I want to do is to get the questions and group_by the QuestionCategory

So I can display my questions like this:

This is the doc to my question: https://docs.djangoproject.com/en/1.8/topics/db/aggregation/

Upvotes: 1

Views: 1477

Answers (1)

Charlesthk
Charlesthk

Reputation: 9684

You do not need GROUP_BY, just use reverse foreignkey lookup:

categories = QuestionCategory.objects.prefetch_related('question_set').all()

for category in categories:
    print category.name
    for question in category.question_set.all():
        print question.question
        print question.answer

In your views.py

def questions(request):
    categories = QuestionCategory.objects.prefetch_related('question_set').all()
    return render(request, 'question.html', {
        'questions': questions
    })

In your question.html

{% for category in categories %}
  <h2>{{ category.name }}</h2>
  {% for question in category.question_set.all %}
    <h3>{{ question.question }}</h3>
    <p>{{ question.answer }}</p>
  {% endfor %}
{% endfor %}

The prefetch_related is use to optimise your query.

Upvotes: 1

Related Questions