Good ways to sort a queryset? - Django

后端 未结 3 635
太阳男子
太阳男子 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:07

    What about

    import operator
    
    auths = Author.objects.order_by('-score')[:30]
    ordered = sorted(auths, key=operator.attrgetter('last_name'))
    

    In Django 1.4 and newer you can order by providing multiple fields.
    Reference: https://docs.djangoproject.com/en/dev/ref/models/querysets/#order-by

    order_by(*fields)

    By default, results returned by a QuerySet are ordered by the ordering tuple given by the ordering option in the model’s Meta. You can override this on a per-QuerySet basis by using the order_by method.

    Example:

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

    The result above will be ordered by score descending, then by last_name ascending. The negative sign in front of "-score" indicates descending order. Ascending order is implied.

提交回复
热议问题