django如何获得对许多领域的计数 [英] django how to get count for manytomany field

查看:50
本文介绍了django如何获得对许多领域的计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有问题模型:

class Question(models.Model):
    user = models.ForeignKey(User)
    title = models.CharField(max_length=120)
    description = models.TextField()
    answers = models.ManyToManyField('Answer',related_name='answer_name', blank=True)
    post_date = models.DateTimeField(auto_now=True)

def __unicode__(self):
    return self.title

我有答案模型:

class Answer(models.Model):
    user = models.ForeignKey(User)
    question = models.ForeignKey(Question)
    ans_body = models.TextField()
    post_date = models.DateTimeField(auto_now=True)

def __unicode__(self):
    return self.ans_body

问题创建和答案提交工作正常。我无法正确显示特定问题的答案。但是,当我尝试获取特定问题的答案数量时,它没有显示。它显示为0。

Question creation and answer submission are working perfectly. I cant correctly show answer for particular question. But when I try to get the count of answer for particular question its not showing. It displays 0 count.

在我看来,我的答案列表是:

In my view I am getting the list of the answer by:

context["question_list"] = Question.objects.all()

在我的模板中

{% for question in question_list %}
   {{ question.title }}
    Ans:{{question.answers.count}}
{% endfor %}

当我这样做时,如果有答案,我将得到计数0。

When I do this I get the count 0 if there are answers. How can I get the count of the answers for particular questions.

推荐答案

这可行:

{{question.answer_set.count}}

快乐..

这篇关于django如何获得对许多领域的计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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