且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

django 外键模型计数

更新时间:2023-12-02 20:59:46

您可以使用.annotate()来获取answers的数量> 与每个问题相关联.

You can use .annotate() to get the count of answers associated with each question.

from django.db.models import Count
questions = Question.objects.annotate(number_of_answers=Count('answer')) # annotate the queryset

通过这样做,每个question 对象将有一个额外的属性number_of_answers,其值为与每个 相关联的answers 的数量问题.

By doing this, each question object will have an extra attribute number_of_answers having the value of number of answers associated to each 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 Count

def all_questions(request):
    questions = Question.objects.annotate(number_of_answers=Count('answer'))
    return render(request, 'all_questions.html', {
            'questions':questions})

在您的模板中,您可以执行以下操作:

In your template, then you can do something like:

{% for question in questions %}
    {{question.number_of_answers}} # displays the number of answers associated with this question