【发布时间】:2014-01-25 04:29:43
【问题描述】:
在我的 Django 应用程序中,我收集了大量的模型,这些模型按完成操作的次数排序。这是一个排行榜。 我希望使用我的应用程序的人看到他们在什么地方,以及上面两个人和下面两个人的名字。所以我需要找到相关用户的位置那个查询集,然后找到他上面和下面的两个用户。实现这一目标的最有效方法是什么?我正在画空白...
【问题讨论】:
标签: python django list django-queryset
在我的 Django 应用程序中,我收集了大量的模型,这些模型按完成操作的次数排序。这是一个排行榜。 我希望使用我的应用程序的人看到他们在什么地方,以及上面两个人和下面两个人的名字。所以我需要找到相关用户的位置那个查询集,然后找到他上面和下面的两个用户。实现这一目标的最有效方法是什么?我正在画空白...
【问题讨论】:
标签: python django list django-queryset
您可以使用score__lt 和score__gt 按分数过滤对象。
class Participant(models.Model):
user = models.ForeignKey(User)
score = models.IntegerField()
def get_score_above_below(self, n):
try:
above = Participant.filter(score__lt=self.score).order_by('-score')[:n]
except ObjectDoesNotExist:
above = Participant.filter(score__lt=self.score).order_by('-score')
try:
below = Participant.filter(score__gt=self.score).order_by('-score')[:n]
except ObjectDoesNotExist:
below = Participant.filter(score__gt=self.score).order_by('-score')
entries = list(above) + [self] + list(below)
return [(part.user, part.score) for part in entries]
这将返回一个元组列表:
[('<username two places above>', score),
('<username one place above>', score),
('<instance username>', score),
('<username one place below>', score),
('<username two places below>', score)]
【讨论】: