在模板中显示外键属性

时间:2014-10-12 23:00:18

标签: django django-models django-templates django-views

我有以下型号:

# models.py
class Site(models.Model):
    name = models.CharField(max_length=75)
    slug = models.SlugField(_('slug'), max_length=75, blank=True, null=True)
    link = models.CharField(max_length=150)
    created_on = models.DateTimeField(auto_now_add=True, editable=False)
    modified_on = models.DateTimeField(auto_now=True)

class SiteRatings(models.Model):
    site = models.ForeignKey('Site', related_name='siterating', blank=True, null=True)
    overall_rating = models.FloatField(blank=True, null=True)
    plans_rating = models.FloatField(blank=True, null=True)
    prices_rating = models.FloatField(blank=True, null=True)
    design_rating = models.FloatField(blank=True, null=True)
    support_rating = models.FloatField(blank=True, null=True)

    def save(self, *args, **kwargs):
        self.overall_rating = (self.plans_rating + self.prices_rating + self.design_rating + self.support_rating)/4

        super(SiteRatings, self).save(*args, **kwargs)

    def __str__(self):
        return self.site.name

我的观点

# views.py
def home(request):
    print(user_language)
    site_list = Site.objects.order_by('-date_launched')
    return render_to_response('index.html', {'site_list': site_list}, RequestContext(request))

在模板中

# template
{% for site in site_list %}
    <h4><span class="label label-info">{{ site.name }}</span></h4>
    <h4><span class="label label-info">{{ site.siterating.overall_rating }}</span></h4>
{% endfor % }

问题在于,当我尝试访问{{ site.siterating.overall_rating }}时,没有返回任何内容,我尝试更改{{ site.siterating.0.overall_rating }}并且它尚未显示。

1 个答案:

答案 0 :(得分:0)

我解决了我的问题。首先在模型中我创建了一个获得网站评级的方法(谢谢karthikr的建议):

#models
class Site(models.Model):
    name = models.CharField(max_length=75)
    slug = models.SlugField(_('slug'), max_length=75, blank=True, null=True)
    link = models.CharField(max_length=150)
    created_on = models.DateTimeField(auto_now_add=True, editable=False)
    modified_on = models.DateTimeField(auto_now=True)

    def get_site_rating(self):
        return self.siterating.filter(site = self)

之后,我转到我的模板并使用了我创建的类方法:

{% for site in site_list %}
    <h4><span class="label label-info">{{ site.name }}</span></h4>
    <h4><span class="label label-info">{{ site.get_site_rating.0.overall_rating }}</span></h4>
 {% endfor % }

请注意,我使用...get_site_rating.0...只是因为在我的情况下我只有1个评级/网站。