【问题标题】:Django Get Range in QuerysetDjango 在查询集中获取范围
【发布时间】:2014-01-25 04:29:43
【问题描述】:

在我的 Django 应用程序中,我收集了大量的模型,这些模型按完成操作的次数排序。这是一个排行榜。 我希望使用我的应用程序的人看到他们在什么地方,以及上面两个人和下面两个人的名字。所以我需要找到相关用户的位置那个查询集,然后找到他上面和下面的两个用户。实现这一目标的最有效方法是什么?我正在画空白...

【问题讨论】:

    标签: python django list django-queryset


    【解决方案1】:

    您可以使用score__ltscore__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)]
    

    【讨论】:

      猜你喜欢
      • 2017-08-05
      • 1970-01-01
      • 2021-12-10
      • 1970-01-01
      • 1970-01-01
      • 2014-12-17
      • 1970-01-01
      • 2014-10-26
      • 2012-03-02
      相关资源
      最近更新 更多