【问题标题】:last record in django models databasedjango模型数据库中的最后一条记录
【发布时间】:2013-04-05 02:31:50
【问题描述】:

我正在尝试这样做:

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

id=1 的位置有 3 个评分:1、2、4。现在当用户搜索评分 2 时,该位置应该出现,因为它的最后一条记录是 4 .

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

我可以这样做吗:

all_locations = Location.objects.all()

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

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

【问题讨论】:

  • 你的型号是什么?

标签: python django django-models


【解决方案1】:

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

【讨论】:

  • 取决于您,您可以在值中添加该名称以便您可以访问它
【解决方案2】:

这纯粹是猜测,但你能做这样的事情吗?

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

【讨论】:

  • 应该是).order_by('-id')[0]。可能还需要包装在 try/catch 中,以防计数为 0
  • @Hamish,是的,try/catch 非常重要。但 order_by 结果也会给出 2。
【解决方案3】:

啊,我误解了这个问题。这是一种不太有效的方法来完成您的要求:

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

【讨论】:

  • 这很糟糕。这正是 Manager 的用途,那么为什么不使用内置功能呢?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多