python - Ordering data after distinct - Stack Overflow

I distinct data by sku_idqueryset = self.filter_queryset(queryset.order_by('sku_id','id&

I distinct data by sku_id

    queryset = self.filter_queryset(queryset.order_by('sku_id','id').distinct('sku_id'))

However this result is not sorted by id,

then I try to

    queryset = self.filter_queryset(queryset.order_by('sku_id','id').distinct('sku_id').order_by('id'))

However this shows the error

ProgrammingError at /api/myfetch/
SELECT DISTINCT ON expressions must match initial ORDER BY expressions
LINE 1: SELECT COUNT(*) FROM (SELECT DISTINCT ON ("myapp_produc...

Is it possible to sort the column after distinct?

I distinct data by sku_id

    queryset = self.filter_queryset(queryset.order_by('sku_id','id').distinct('sku_id'))

However this result is not sorted by id,

then I try to

    queryset = self.filter_queryset(queryset.order_by('sku_id','id').distinct('sku_id').order_by('id'))

However this shows the error

ProgrammingError at /api/myfetch/
SELECT DISTINCT ON expressions must match initial ORDER BY expressions
LINE 1: SELECT COUNT(*) FROM (SELECT DISTINCT ON ("myapp_produc...

Is it possible to sort the column after distinct?

Share Improve this question asked Mar 4 at 10:56 whitebearwhitebear 12.5k29 gold badges149 silver badges299 bronze badges 1
  • It might be because you count (see SELECT COUNT(*)). Can you share the ful traceback? – willeM_ Van Onsem Commented Mar 4 at 11:17
Add a comment  | 

2 Answers 2

Reset to default 0

Last time I checked, you need to use a Subquery to get the expected behavior with postgres backend:

from django.db.models import Subquery

your_objects = YourObjectClass.objects.filter(sku_id__in=Subquery(YourObjectClass.objects.distinct('sku_id').values('sku_id'))).order_by('id')

This should get you records with distinct sku_ids ordered by ascending id.

When you use distinct('sku_id') in Django it translates to DISTINCT ON (sku_id) in PostgreSQL. It's like a feature in PostgreSQL that requires to point in ORDER BY the same column as in DISTINCT.

In your second query you try to reorder by id, which PostgreSQL doesn't allow.

Solution:

queryset = self.filter_queryset(
    queryset.order_by('sku_id', 'id').distinct('sku_id')
).order_by('id')

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745048759a4608256.html

相关推荐

  • python - Ordering data after distinct - Stack Overflow

    I distinct data by sku_idqueryset = self.filter_queryset(queryset.order_by('sku_id','id&

    7小时前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信