最后记录在django模型数据库 [英] last record in django models database

查看:128
本文介绍了最后记录在django模型数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试这样做:

我有一个位置的评级记录表。在这个表格中,一个位置也可以有多个评分。但是我想将搜索限制在同一位置的最后一个记录。例如:

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:

一个位置与 id = 1有3个评分:1,2,4.现在用户搜索评分分数2,此位置应出现,因为其最后一条记录为4.

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.

编辑

有两个表(django模型):位置和评级。

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

我可以这样做:

all_locations = Location.objects.all()

然后在模板中。 locations_rating 是评级表中外键 locationID 的相关名称。

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

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


推荐答案

models.py

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

这篇关于最后记录在django模型数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆