您可以 使用.annotate()
获得的计数
answers与各关联
question。
from django.db.models import Countquestions = Question.objects.annotate(number_of_answers=Count('answer')) # annotate the queryset
这样,每个
question对象将具有一个额外的属性
number_of_answers,该属性的值与每个对象
answers相关联
question。
questions[0].number_of_answers # access the number of answers associated with a question using 'number_of_answers' attribute
最终代码:
from django.db.models import Countdef all_questions(request): questions = Question.objects.annotate(number_of_answers=Count('answer')) return render(request, 'all_questions.html', { 'questions':questions})
在模板中,您可以执行以下 *** 作:
{% for question in questions %} {{question.number_of_answers}} # displays the number of answers associated with this question
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)