如何在每个图片的模板计数中显示?

时间:2013-03-12 09:17:42

标签: django

class Picture(models.Model):
    title = models.CharField(max_length=255)

class PictureRate(models.Model):
    user = models.ForeignKey(User)
    picture = models.ForeignKey(Picture)
    rate = models.DecimalField(max_digits=2,decimal_places=1)

的观点:

def index(request):
    pictures = Picture.objects.all()
    return render_to_response('index.html',{'pictures':pictures}, context_instance=RequestContext(request))
模板中的

{% for p in pictures %}
    {{ p.title }}
{% endfor %}

如何在rate每个Picture的模板中显示评分({{1}})?

2 个答案:

答案 0 :(得分:0)

要获得对象外键关系,请按照_set

进行操作
{{ p.picturerate_set.rate }} #to access it's field.
{{ p.picturerate_set.count }} #to count the number of rates your picture has.

答案 1 :(得分:0)

你应该使用注释:

from django.db.models import Count
pictures = Picture.objects.all().annotate(rating_count=Count('picturerate'))

并在模板中:

{{ p.rating_count }}