这是我的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)
问题(2)
...
Question_Category(2)
问题(3)
问题(...)
...
这是我的问题的文档:https://docs.djangoproject.com/en/1.8/topics/db/aggregation/
答案 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用于优化您的查询。