doniyor
doniyor

Reputation: 37856

last record in django models database

i am trying to do this:

i have a table of rating records of locations. in this table, one location can also have multiple rating scores. but i want to restrict the search only to the last record of same locations. for example:

one location with id=1 has 3 rating scores: 1, 2, 4. now when user searchs for rating score 2, this location should NOT appear, because its last record is 4.

EDIT
there are two tables(django models): location and rating.

can i do this:

all_locations = Location.objects.all()

then in template. locations_rating is a related_name for foreignkey locationID in rating table.

{% for location in all_locations %}
  {{ location.locations_rating }}
{% endfor %}

Upvotes: 0

Views: 316

Answers (3)

catherine
catherine

Reputation: 22808

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 %}

Upvotes: 3

kufudo
kufudo

Reputation: 2833

Ahh, I misinterpreted the question. Here's a not very efficient way to do what you're asking:

locations = Location.objects.all();
filtered = []
for location in locations:
    try:
        r = Rating.objects.filter(location=location).order_by(-id).[0]
        if r.rating = 2:
        filtered.append(location)
    except Exception as ex:
        pass

Upvotes: 0

kufudo
kufudo

Reputation: 2833

This is pure guessing, but can you do something like this?

Rating.objects.filter(location_id=1).order_by(id).reverse()[0]

Upvotes: 1

Related Questions