4

i am trying to show the latest rating score of a location. i have 2 tables(django models)

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

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

now in my db, one location(id=1) has 3 ratings(1,2,4).

i want to show the latest record in rating for a location. can i do this in template using related Manager somehow?

my vision is:

all_locs = Location.objects.all()

then in template:

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

can relatedmanager do this kind of things?

doniyor
  • 36,596
  • 57
  • 175
  • 260

1 Answers1

7

My answer in your other related question:

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()

template

{% for location in all_locs %}
   {{ location.locationname }} - {{ location.latest.rating }}<br/>
{% endfor %}
catherine
  • 22,492
  • 12
  • 61
  • 85