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}})?
答案 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 }}