sourcecode

쿼리 세트를 정렬하는 좋은 방법은 무엇입니까? - 장고

codebag 2023. 7. 17. 20:58
반응형

쿼리 세트를 정렬하는 좋은 방법은 무엇입니까? - 장고

제가 하려는 것은 다음과 같습니다.

  • 가장 높은 점수를 받은 30명의 저자(Author.objects.order_by('-score')[:30])

  • 저자를 순서대로 배열하다last_name


좋은 의견이라도 있나?

어때

import operator

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

장고 1.4 이상에서는 여러 필드를 제공하여 주문할 수 있습니다.
참조: https://docs.djangoproject.com/en/dev/ref/models/querysets/ #주문 기준

order_by(

기본적으로 결과가 반환됩니다.QuerySet주문 튜플에 의해 주문됩니다.ordering모델의 메타에 옵션이 있습니다.다음을 사용하여 쿼리 집합별로 이를 재정의할 수 있습니다.order_by방법.

예:

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

위의 결과는 다음과 같이 주문될 것입니다.score내림차순으로last_name상행의앞에 있는 부정적인 표시는"-score"내림차순을 나타냅니다.오름차순이 포함됩니다.

기본 제공 솔루션(SQL 전용)이 항상 최상의 솔루션은 아니라는 것을 보여드리고 싶었습니다.처음엔 장고가 그렇게 생각했어요QuerySet.objects.order_by메소드는 여러 개의 인수를 허용하므로 쉽게 연결할 수 있습니다.

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

하지만, 당신이 기대하는 것처럼 작동하지 않습니다.대표적인 예로, 첫 번째는 점수별로 정렬된 대통령 목록입니다(더 쉽게 읽을 수 있도록 상위 5명 선택).

>>> 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)

다음 기준으로 정렬된 상위 5명의 사용자를 정확하게 제공하는 Alex Martelli의 솔루션 사용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)

그리고 이제 합쳐진 것들은order_by호출:

>>> 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)

보시다시피 첫 번째와 동일한 결과입니다. 즉, 예상했던 것처럼 작동하지 않습니다.

컷오프 점수를 동점으로 만드는 방법은 다음과 같습니다.

author_count = Author.objects.count()
cut_off_score = Author.objects.order_by('-score').values_list('score')[min(30, author_count)]
top_authors = Author.objects.filter(score__gte=cut_off_score).order_by('last_name')

이런 식으로 top_authors에 30명 이상의 저자가 있을 수 있습니다.min(30,author_count)작가가 30명 미만인 경우가 있습니까?

언급URL : https://stackoverflow.com/questions/2412770/good-ways-to-sort-a-queryset-django

반응형