๐Ÿ“’ [ TIL ] 2022.08.05_77์ผ์ฐจ # ์ตœ์ข… ํ”„๋กœ์ ํŠธ ๊ฐœ์„ (1)

๋ฌธ๋ช…์ฃผยท2022๋…„ 8์›” 8์ผ
0

[ 2022-08-05 (๊ธˆ) ์˜ค๋Š˜์˜ TIL ]

[ Today Project ]

drf ๋ฐฑ์—”๋“œ๊ฐœ๋ฐœ + ํ”„๋ก ํŠธ๊ฐœ๋ฐœ
: ์ด๋ฒˆ ํ”„๋กœ์ ํŠธ๋Š” ํŒ€ํ”„๋กœ์ ํŠธ๋กœ ์‹œ์ž‘ํ•ฉ๋‹ˆ๋‹ค.

[ Today Learn ]

  • ๋ฆฌํŒฉํ† ๋ง์ง„ํ–‰
  • ์™ธ๋ž˜ํ‚คํ•„๋“œ ์นด์šดํŠธ

โœ๏ธ ๋‚ด๊ฐ€ ๋ฐฐ์šด๊ฒƒ, ์–ป์€๊ฒƒ

ํˆฌํ‘œ์ˆ˜๋ฅผ ๋งŽ์ด ๋ฐ›์€ ๊ฒŒ์‹œ๊ธ€ ์ˆœ์„œ๋Œ€๋กœ ๋ฆฌ์ŠคํŒ… ๋˜๋Š” ์ธ๊ธฐ ๊ฒŒ์‹œํŒ์„ ๋งŒ๋“œ๋Š” ๊ณผ์ •์—์„œ,

ArticleModel์—์„œ MTM ํ•„๋“œ๋กœ ์ฐธ์กฐํ•˜๊ณ  ์žˆ๋Š” vote๋ฅผ count()ํ•˜์—ฌ ํˆฌํ‘œ์ˆ˜์— ๋”ฐ๋ผ order_by๋ฅผ ํ•˜๊ณ  ์‹ถ์—ˆ๋‹ค.

์ด๋Ÿฌํ•œ ์ƒํ™ฉ์—์„œ django์˜ aggregation, annotage๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋‹ค.

๐Ÿงฉ ๊ณต์‹ ๋ฌธ์„œ ์ฐธ๊ณ 
https://docs.djangoproject.com/en/4.1/topics/db/aggregation/

๊ณต์‹ ๋ฌธ์„œ ๋‚ด์šฉ

๐Ÿงฉ ์ ์šฉ ์˜ˆ์‹œ

# ๋ฉ”์ธํŽ˜์ด์ง€์šฉ ํˆฌํ‘œ์ˆœ ํƒ‘6 ๋ฆฌ์ŠคํŒ…
class MostVotedArticleView(APIView):
    def get(self, request):
        vote = ArticleModel.objects.annotate(num_vote=Count('articlevotebridge')).order_by('-num_vote')[:6][::-1]
        # articles = list(ArticleModel.objects.all().values())
        # articles_id = []
        # for article in articles:
        #     articles_id.append(article['id'])
        # vote_counts = []
        # for id in articles_id:
        #     vote_count = ArticleVoteBridge.objects.filter(article_id=id).count()
        #     vote_counts.append(vote_count)
        # count_list = { name:value for name, value in zip(articles_id, vote_counts)}
        # vote_rank = sorted(count_list.items(), key=lambda x: x[1], reverse=True)[:6]
        # print(vote_rank)
        # rank_articles = []
        # for rank in range(len(vote_rank)):
        #     ranker = vote_rank[rank][0]
        #     rank_articles.append(ranker)
        # print(rank_articles)
        # article_rank = ArticleModel.objects.filter(id__in = rank_articles)[::-1]
        return Response(ArticleSerializer(vote, many=True).data)

์•„๋ž˜์˜ ์ฃผ์„์€ django์˜ aggregation ๊ฐœ๋…์„ ๋ชฐ๋ž์„๋•Œ, ์–ด๋–ป๊ฒŒ๋“  ๊ตฌํ˜„ํ•ด๋ณด๋ ค๊ณ  ๋‚˜๋ฆ„ ๋…ธ๋ ฅํ–ˆ๋˜ ์ฝ”๋“œ์˜€๋Š”๋ฐ aggregation์„ ์ด์šฉํ•˜๋‹ˆ ๊ทธ๋ƒฅ ํ•œ ์ค„๋กœ ๊น”๋”ํ•˜๊ฒŒ ์›ํ•˜๋Š” ๊ฐ’์„ ์ถœ๋ ฅํ•  ์ˆ˜ ์žˆ์—ˆ๋‹ค.

profile
ํ•˜๋ฃจ ํ•œ๊ฑธ์Œ์”ฉ ๊พธ์ค€ํžˆ ๋‚˜์•„๊ฐ€๋Š” ๊ฐœ๋ฐœ์ž๐Ÿ™†โ€โ™€๏ธ https://github.com/Moonmooj

0๊ฐœ์˜ ๋Œ“๊ธ€

๊ด€๋ จ ์ฑ„์šฉ ์ •๋ณด