Django GROUP BY 外键查询
Django GROUP BY ForeignKey query
这是我的 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/
您不需要 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 用于优化您的查询。
这是我的 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/
您不需要 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 用于优化您的查询。