Django GROUP BY ForeignKey查询

时间:2015-05-18 18:05:36

标签: group-by

这是我的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)

我想要做的是提出问题并group_by QuestionCategory

所以我可以这样显示我的问题:

  • Question_Category(1)

    • 问题(1)

      • 答案(1)
    • 问题(2)

      • 答案(2)

    ...

  • Question_Category(2)

    • 问题(3)

      • 答案(3)
    • 问题(...)

      • 回答(...)

    ...

这是我的问题的文档:https://docs.djangoproject.com/en/1.8/topics/db/aggregation/

1 个答案:

答案 0 :(得分:0)

您不需要GROUP_BY,只需使用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

views.py

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

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

prefetch_related用于优化您的查询。