django 外键模型计数 [英] django count of foreign key model

查看:33
本文介绍了django 外键模型计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Hi i want to display a count of answers to my question model

我的模型:

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

现在视图显示所有答案的计数.我如何通过 Question 模型过滤它?

Right now view displays count of all answers. How can i filter it by the Question model?

推荐答案

您可以使用.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

这篇关于django 外键模型计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆