Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
704 views
in Technique[技术] by (71.8m points)

python - django how to get count for manytomany field

I have model for question:

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

And I have model for answer:

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

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

And in my template

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This worked:

{{question.answer_set.count}}

Happy..


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...