django算上外键模型

时间:2015-10-07 17:21:28

标签: 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)

我的观点:

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 })

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

2 个答案:

答案 0 :(得分:12)

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

from django.db.models import Count
questions = 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 Count

def 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

答案 1 :(得分:3)

请参阅docs
您可以注释查询,例如:

from django.db.models import Count
questions = Question.objects.annotate(num_answer=Count('answer'))

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

def all_questions(request):
    questions = Question.objects.all()
    return render(request, 'all_questions.html', {'questions':questions })

现在,在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 %}

效率更高。