最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - Ordering data after distinct - Stack Overflow

programmeradmin1浏览0评论

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')
发布评论

评论列表(0)

  1. 暂无评论