본문 바로가기
Programming/Django

Django | 함수형 뷰 vs 클래스형 뷰(GET/POST 요청 처리 방식 비교)

by Mandy's 2025. 7. 29.

Django로 블로그를 만들다 보면 댓글 작성 기능처럼 GET과 POST 요청을 함께 처리해야 하는 경우가 많다.
이럴 땐 함수형 뷰로도 충분히 처리할 수 있지만, 클래스형 뷰(View)를 사용하면 코드가 더 명확해진다.

오늘은 댓글 작성 기능을 예로 들며 함수형 뷰와 클래스형 뷰를 비교해 보겠다.


👀 1. 기존 함수형 뷰 코드

def post_detail(request, slug):
    post = get_object_or_404(Post, slug=slug)

    if request.method == 'POST':
        comment_form = CommentForm(request.POST)
        if comment_form.is_valid():
            comment = comment_form.save(commit=False)
            comment.post = post
            comment.save()
            return redirect("post-detail-page", slug=slug)
    else:
        comment_form = CommentForm()

    return render(request, "blog/post-detail.html", {
        "post": post,
        "post_tags": post.tags.all(),
        "comments": post.comments.all(),
        "comment_form": comment_form
    })

✅ 장점

  • 간단한 구조로 빠르게 구현 가능
  • 한눈에 GET/POST 처리를 파악할 수 있음

❌ 단점

  • request.method 조건문으로 로직이 분기됨 → 가독성이 떨어짐
  • 코드가 길어지고 복잡해질수록 유지보수가 힘듦

⚙️ 2. 클래스형 뷰(View)로 리팩토링

from django.views import View

class SinglePostView(View):
    def get(self, request, slug):
        post = get_object_or_404(Post, slug=slug)
        comment_form = CommentForm()
        context = {
            "post": post,
            "post_tags": post.tags.all(),
            "comments": post.comments.all(),
            "comment_form": comment_form
        }
        return render(request, "blog/post-detail.html", context)

    def post(self, request, slug):
        post = get_object_or_404(Post, slug=slug)
        comment_form = CommentForm(request.POST)
        if comment_form.is_valid():
            comment = comment_form.save(commit=False)
            comment.post = post
            comment.save()
            return redirect("post-detail-page", slug=slug)

        context = {
            "post": post,
            "post_tags": post.tags.all(),
            "comments": post.comments.all(),
            "comment_form": comment_form
        }
        return render(request, "blog/post-detail.html", context)

✅ 장점

  • GET과 POST 요청을 함수로 명확하게 분리
  • 코드 구조가 DRY(Don’t Repeat Yourself) 하고 가독성이 높음
  • Django의 클래스형 뷰(ListView, CreateView, DetailView) 등과 호환이 좋음

🔄 코드 비교 요약

항목 함수형 뷰 클래스형 뷰

요청 분기 if request.method == 'POST' get() / post() 함수로 분리
가독성 중간 이상 (조건문 많아짐) 높음 (책임 분리됨)
확장성 기능 많아질수록 복잡 메서드 기반으로 유지보수 쉬움
적합한 경우 간단한 로직 복잡한 로직, 재사용 구조 필요

✨ 마무리

단순히 "작동하는 코드"에서 그치지 않고, "유지보수 가능한 구조"를 고민하는 것이 중요하다.
클래스형 뷰는 처음엔 익숙하지 않을 수 있지만, 점점 더 깔끔하고 확장 가능한 코드를 만들 수 있게 도와준다.

앞으로 더 많은 기능을 추가하고 싶다면, 지금부터 클래스형 뷰에 익숙해지자!


필요하시면 블로그에 올릴 때 사용할 썸네일이나 문장 스타일도 같이 다듬어 드릴 수 있어요!