하루일문

[Django] M:M 정렬 본문

django

[Django] M:M 정렬

support_u 2023. 5. 3. 16:21

annotate :  메소드는 쿼리셋 내의 객체들에 대한 추가적인 정보를 가져올 때 사용합니다. 주로 집계 함수를 사용하여 각 객체들의 특정 값을 계산하거나, 필드에 대한 통계를 내거나, 다른 모델과의 관계를 계산하는 등의 작업에 사용

 

views.py

from django.db.models import Count

def index(request):
    articles = Article.objects.all()
    if request.method == 'GET':
    	# 명령어를 받아준다
        order = request.GET.get('order')
        if order == "2":
        	# 다대다 관계일땐 annotate로 정의 후 정렬
            articles = articles.annotate(like_count=Count('like_users')).order_by('-like_count', '-pk')
        elif order == "3":
            articles = articles.annotate(view_count=Count('views')).order_by('-view_count', '-pk')
        else:
            articles = articles.order_by('-pk')
    else:
        articles = articles.order_by('-pk')
    
    context = {
        'articles': articles,
    }
    return render(request, 'articles/index.html', context)

 

 template

      <form  method='GET' class='main--form--wrap'>
        <select name='order' class="form-select me-2">
          <option value="1">최신글</option>
          <option value="2">인기글</option>
          <option value="3">많이본 글</option>
        </select>
        <input type="submit" value='정렬' class="btn btn-secondary btn-sm">
      </form>