Good ways to sort a queryset? - Django

后端 未结 3 630
太阳男子
太阳男子 2020-12-02 05:37

what I\'m trying to do is this:

  • get the 30 Authors with highest score ( Author.objects.order_by(\'-score\')[:30] )

  • order the au

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-02 06:13

    I just wanted to illustrate that the built-in solutions (SQL-only) are not always the best ones. At first I thought that because Django's QuerySet.objects.order_by method accepts multiple arguments, you could easily chain them:

    ordered_authors = Author.objects.order_by('-score', 'last_name')[:30]
    

    But, it does not work as you would expect. Case in point, first is a list of presidents sorted by score (selecting top 5 for easier reading):

    >>> auths = Author.objects.order_by('-score')[:5]
    >>> for x in auths: print x
    ... 
    James Monroe (487)
    Ulysses Simpson (474)
    Harry Truman (471)
    Benjamin Harrison (467)
    Gerald Rudolph (464)
    

    Using Alex Martelli's solution which accurately provides the top 5 people sorted by last_name:

    >>> for x in sorted(auths, key=operator.attrgetter('last_name')): print x
    ... 
    Benjamin Harrison (467)
    James Monroe (487)
    Gerald Rudolph (464)
    Ulysses Simpson (474)
    Harry Truman (471)
    

    And now the combined order_by call:

    >>> myauths = Author.objects.order_by('-score', 'last_name')[:5]
    >>> for x in myauths: print x
    ... 
    James Monroe (487)
    Ulysses Simpson (474)
    Harry Truman (471)
    Benjamin Harrison (467)
    Gerald Rudolph (464)
    

    As you can see it is the same result as the first one, meaning it doesn't work as you would expect.

提交回复
热议问题