django算上外键模型

Iva*_*kin 7 python django django-models django-views

嗨,我想显示我的问题模型的答案数

我的模特:

class Question(models.Model):

    text = models.TextField()
    title = models.CharField(max_length=200)
    date = models.DateTimeField(default=datetime.datetime.now)
    author = models.ForeignKey(CustomUser)
    tags = models.ManyToManyField(Tags)

    def __str__(self):
        return self.title


class Answer(models.Model):

    text = models.TextField()
    date = models.DateTimeField(default=datetime.datetime.now)
    likes = models.IntegerField(default=0)
    author = models.ForeignKey(CustomUser)
    question = models.ForeignKey(Question)
Run Code Online (Sandbox Code Playgroud)

我的看法:

def all_questions(request):

    questions = Question.objects.all()
    answers = Answer.objects.filter(question_id=questions).count()

    return render(request, 'all_questions.html', {
            'questions':questions, 'answers':answers })
Run Code Online (Sandbox Code Playgroud)

正如预期的那样,查看所有答案的显示计数.对于每个问题模型,我如何过滤此计数?

Rah*_*pta 15

您可以使用.annotate()来获取answers与每个相关联的计数question.

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

通过这样做,每个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
Run Code Online (Sandbox Code Playgroud)

最终守则:

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})
Run Code Online (Sandbox Code Playgroud)

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

{% for question in questions %}
    {{question.number_of_answers}} # displays the number of answers associated with this question
Run Code Online (Sandbox Code Playgroud)


Pau*_*soa 5

查看文档
您可以对查询进行注释,例如:

from django.db.models import Count
questions = Question.objects.annotate(num_answer=Count('answer'))
Run Code Online (Sandbox Code Playgroud)

但是,将代码重构为此。删除答案的数量:

def all_questions(request):
    questions = Question.objects.all()
    return render(request, 'all_questions.html', {'questions':questions })
Run Code Online (Sandbox Code Playgroud)

现在,在all_question.html. 只需使用:

{% for question in questions %}
    Title: {{question.title}}
    Count Answers: {{question.answer_set.all|length}}
    {% for answer in question.answer_set.all %}
        {{answer.text}}
    {% endfor %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

它更有效率。

  • 您不需要在模型中添加字段计数,即 'annotate' 。当指定 annotate() 子句时,QuerySet 中的每个对象都将使用指定的值进行注释。 (2认同)