[Python] Orderby and distinct at the same time

Discussão em 'Python' iniciado por Stack, Maio 12, 2025.

  1. Stack

    Stack Membro Participativo

    I have tabels like this

    id sku
    1 C
    2 B
    3 C
    4 A


    Finally I want to get the raws like this.

    1 C
    2 B
    4 A


    At first I use distinct

    queryset = self.filter_queryset(queryset.order_by('sku').distinct('sku'))


    It depicts the raw like this,

    4 A
    1 C
    2 B


    Then now I want to sort this with id,

    queryset = queryset.order_by('id')


    However it shows error like this,

    django.db.utils.ProgrammingError: SELECT DISTINCT ON expressions must match initial ORDER BY expressions
    LINE 1: SELECT DISTINCT ON ("defapp_log"."sku") "d...

    Continue reading...

Compartilhe esta Página