【问题标题】:django + postgres and select distinctdjango + postgres 并选择不同的
【发布时间】:2016-08-19 19:21:06
【问题描述】:

我正在使用 postgres 运行 django,我需要从表中查询一些记录,按等级对它们进行排序,并获得关于外键的唯一条目。

基本上我的模型是这样的:

class BookingCatalog(models.Model):
   .......
   boat = models.ForeignKey(Boat, verbose_name=u"Boat", related_name="booking_catalog")
   is_skippered = models.BooleanField(u'Is Skippered',choices=SKIPPER_CHOICE, default=False) 
   rank = models.IntegerField(u"Rank", default=0, db_index=True)
   .......

这个想法是运行这样的东西

  BookingCatalog.objects.filter (...).order_by ('-rank', 'boat', 'is_skippered').distinct ('boat')

不幸的是,这不起作用,因为我使用的是引发此异常的 postgres:

SELECT DISTINCT ON 表达式必须匹配初始 ORDER BY 表达式

我应该怎么做?

【问题讨论】:

    标签: django postgresql django-models


    【解决方案1】:

    The distinct argument has to match the first order argument。试试这个:

    BookingCatalog.objects.filter(...) \
                          .order_by('boat', '-rank', 'is_skippered') \
                          .distinct('boat')
    

    【讨论】:

      【解决方案2】:

      我这样做的方法是首先选择不同的对象,然后使用这些结果过滤另一个查询集。

      # Initial filtering
      result = BookingCatalog.objects.filter(...)
      
      # Make the results distinct
      result = result.order_by('boat').distinct('boat')
      
      # Extract the pks from the result
      result_pks = result.values_list("pk", flat=True)
      
      # Use those result pks to create a new queryset
      restult_2 = BookingCatalog.objects.filter(pk__in=result_pks)
      
      # Order that queryset
      result_2 = result_2.order_by('-rank', 'is_skippered')
      
      print(result_2)
      

      我相信这会导致执行单个查询,其中包含一个子查询。不过,我希望对 Django 有更多了解的人来证实这一点。

      【讨论】:

        【解决方案3】:

        ..ordering by -rank 将为您提供每个重复项的最低排名,但您的整体查询结果将按船字段排序

        BookingCatalog.objects.filter (...).order_by('boat','-rank','is_skippered').distinct('boat')
        

        有关更多信息,请参阅Django documentation ,包括 Postgres

        【讨论】:

          猜你喜欢
          • 2011-04-11
          • 2017-12-14
          • 2016-10-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-08-05
          • 2016-05-03
          • 1970-01-01
          相关资源
          最近更新 更多