我有一个Users表和一个Scores表。每个分数都有一个created_at时间戳,并与用户相关联;用户可能有多个分数。它们在user和created_at上是唯一的。如何返回最近得分最低的用户?我知道如何在原始sql中执行此操作,不知道如何在queryset中执行此操作。这是我的尝试:
from .models import User
users = User.objects.all().order_by('score__score')[:5]
然而,这只是所有时间分数最低的用户排序 - 我想只为每个用户使用最近创建的分数。在SQL中,代码是
SELECT u.user, t.score FROM
users u JOIN
(SELECT s.user, s.score FROM
scores s JOIN
(SELECT user, max(created_at) created_at FROM
scores
GROUP BY user) c
ON s.user = c.user AND s.created_at = c.created_at
) t
ON u.user = t.user
ORDER BY score
LIMIT 5
编辑:添加模型
class User(models.Model):
name = models.CharField(max_length=60)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.name
class Score(models.Model):
user_id = models.ForeignKey(User)
score = models.FloatField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __unicode__(self):
return str(self.score)