Django外键模型计数

Django外键模型计数,第1张

Django外键模型计数

您可以 使用

.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


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5617324.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存