Django로 조회수 count 기능 구현하기

Choi Rim·2021년 11월 2일
1

Django

목록 보기
21/21
post-thumbnail

Django로 조회수 count 기능을 구현해보자! 😎

class PostView(View):
    def get(self,request,post_id):
        if not Post.objects.filter(id = post_id).exists():
            return JsonResponse({'MESSAGE' : 'DOES_NOT_EXIST_POST'}, status = 404)

        post = Post.objects.get(id = post_id)

        post.counting += 1 
        post.save()

        result = {
                'author'     : post.author,
                'title'      : post.title,
                'content'    : post.content,
                'created_at' : post.created_at.strftime('%Y-%m-%d %H:%M:%S'),
                'counting'   : post.counting
        }

        return JsonResponse({"RESULT" : result}, status = 200)

아주 간단하게 구현하려면 post.counting += 1 으로 counting 행을 조회할 때마다 1씩 늘려주면 된다. post.save()로 변경 결과를 저장해준다. 하지만 이렇게 하면 새로고침 할 때마다 무한대로 조회수가 count 된다. (옛날에 싸이월드 조회수 조작 기계가 생각나네요..)

User가 같을 시에는 조회수가 늘어나지 않도록 구현해보자

어떻게 login하지 않은 유저를 식별할까 생각해보다가 유저의 ip주소로 식별하기로 하였다.

def get_client_ip(request):
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip

위와 같이 ip를 리턴해주는 get_client_ip class를 작성한다.

class PostView(View):
    def get(self,request,post_id):
        if not Post.objects.filter(id = post_id).exists():
            return JsonResponse({'MESSAGE' : 'DOES_NOT_EXIST_POST'}, status = 404)

        post = Post.objects.get(id = post_id)

        ip = get_client_ip(request)

        if not Saveip.objects.filter(access_ip=ip, post_id=post_id).exists():
            post.counting += 1 
            post.save()
            
            Saveip.objects.create(
                access_ip = ip,
                post_id   = post_id
        )

        result = {
                'author'     : post.author,
                'title'      : post.title,
                'content'    : post.content,
                'created_at' : post.created_at.strftime('%Y-%m-%d %H:%M:%S'),
                'counting'   : post.counting
        }

        return JsonResponse({"RESULT" : result}, status = 200)

👉 PostView에서 get_client_ip에서 ip 주소를 받아온다.
👉 db를 조회하여 ip주소와 post_id 모두 일치하는 데이터가 없을 시 조회수를 1번 카운팅한다.
👉 카운팅한 뒤 해당 글을 조회한 유저 ip와 해당 글의 id를 db에 저장한다.

이렇게 하면 db에 해당 글을 조회한 유저 ip와 조회된 글의 id가 저장되어 있어 조회수가 무한정 늘어나는 것을 막을 수 있다 😇

profile
https://rimi0108.github.io/

0개의 댓글