1
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

4

2 回答 2

0

要获得你这样做的对象外键关系,请通过它的_set.

{{ p.picturerate_set.rate }} #to access it's field.
{{ p.picturerate_set.count }} #to count the number of rates your picture has.
于 2013-03-12T09:25:44.607 回答
0

您应该使用注释:

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

并在模板中:

{{ p.rating_count }}
于 2013-03-12T10:14:38.563 回答