(Django) annotate로 좋아요와 댓글순으로 filter하기
annotate는 장고의 쿼리표현식 중 하나로 like나 comment의 합계를 구할 수 있다.
이때 like나 comment가 Article의 필드로 써져 있지 않아도 annotate를 사용하여 합계를 구할 수 있다.
아래는 Article에 쓰인 comment의 합계를 Count를 통해 구한다음 review_count라는 변수에 담았다. 이후 바로 order_by를 사용하여 review_count가 많은 article순으로 오름차순하는 로직이다.
Article 모델안에는 comment라는 필드가 존재하지 않지만 Article를 Comment가 comment라는 related_name으로 참조하고 있기 때문에 값을 구할 수 있다
댓글순 filter하기
articles = Article.objects.filter(q, is_deleted=False).annotate(review_count=Count('comment')).order_by('-review_count','-created_at')
아래는 Article에 눌린 좋아요 개수를 Count를 통해 구한 다음 like_count라는 변수에 담았다.
이후 order_by를 사용하여 like_count가 많은 article순으로 오름차순하는 로직이다.
위의 comment와 다른 점은 comment에서는 Foreign key로 참조하고 있기 때문에 1:n에서 n의 개수를 구하는 로직이였다.
하지만 like에서는 Article을 참조하고 있는 필드가 OneToOneField로 묶여 있기 때문에 Like안에 있는 users의 개수를 세어주어야 한다. like__users
를 이용해서 article를 참조하고 있는 related_name인 like의 users에 접근을 하여 합계를 구해주었다
좋아요순 filter하기
articles = Article.objects.filter(q, is_deleted=False).annotate(like_count=Count('like__users')).order_by('-like_count','-created_at')