开发者

How to get numer of objects/elements (Foreign Key) in template

how to get number of answer开发者_如何学JAVAs for question

class Answers(models.Model):
    ...
    question = models.ForeignKey(Question, related_name='Question')

when I

return render_to_response('profile.xhtml',
                      {'questions': Question.objects.filter(author=details_profile),},
                      context_instance=RequestContext(request))

and in template i wanna get number of answers for each question ({{ q.answer.count }} is just a example)

{% for q in questions %}
    {{ q.title }}, Answers: {{ q.answer.count }}
{% endfor %}

nvm i just make in models.py

class Question(models.Model):
    ...
    def count_it(self):
        return Answers.objects.filter(question=self).count()

and use in template {{ q.count_it }}


If you hadn't set related_name='Question', you'd be able to get the count in the template like this:

{{ q.answer_set.count }}

...because "answer_set" is the default related_name. As is, you should be able to use:

{{ q.Question.count }}

But that's ugly! Hopefully you've figured out by now that the related_name is the name you want to use to refer back to the current model from the model you're referencing in your ForeignKey. So the best option would be something like:

class Answers(models.Model):
    ...
    question = models.ForeignKey(Question, related_name='answers')

and then in the template:

{% for q in questions %}
    {{ q.title }}, Answers: {{ q.answers.count }}
{% endfor %}


{% for q in questions %}
    {{ q.title }}, Answers: {{ q.Question|length }}
{% endfor %}

I would recommend changing your related name there to something like 'answers' or something.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜