2013-04-05 38 views
3

我想显示一个位置的最新评分。我有2桌(Django模型)django相关经理 - 在模板

Class Location(models.Model): 
    locationname = models.CharField() 
    ... 

Class Rating(models.Model): 
    von_location = models.ForeignKey(Location,related_name="locations_rate") 
    rating = models.IntegerField() 

现在在我的分贝,一个位置(id = 1)有3评级(1,2,4)。

我想显示位置评分的最新记录。我可以使用相关的管理器以某种方式在模板中执

我的理想是:

all_locs = Location.objects.all() 

然后在模板:

{% for location in all_locs %} 
    {{ location.locations_rate.latest }} 
{% endfor %} 

可以relatedmanager做这样的事情呢?

+0

只是把它作为一个参数渲染模板函数? – 2013-04-05 03:27:48

+1

答案:http://stackoverflow.com/questions/15824934/last-record-in-django-models-database – catherine 2013-04-05 03:41:28

回答

5

我在你的其他相关问题的答案:

models.py

class Location(models.Model): 
    locationname = models.CharField(max_length=100) 

    def __unicode__(self): 
     return self.locationname 

    def latest(self): 
     return Rating.objects.values('rating').filter(von_location=self).order_by('-id')[0] 

class Rating(models.Model): 
    von_location = models.ForeignKey(Location,related_name="locations_rate") 
    rating = models.IntegerField() 

    def __unicode__(self): 
     return "{0}".format(self.rating) 

views.py

all_locs = Location.objects.all() 

模板

{% for location in all_locs %} 
    {{ location.locationname }} - {{ location.latest.rating }}<br/> 
{% endfor %}