我正在尝试显示某个地点的最新评分。我有 2 个表(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能做这种事吗?
最佳答案
我在你的其他相关问题中的回答:
模型.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)
View .py
all_locs = Location.objects.all()
模板
{% for location in all_locs %}
{{ location.locationname }} - {{ location.latest.rating }}<br/>
{% endfor %}
关于python - django 相关管理器 - 在模板中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15825362/