본문 바로가기
개발하면서적는글

[django/python] Serializer 필요한 이유

by 옥수수왕자 2022. 10. 15.

django rest framework을 알기 전에 JsonResponse의 쓰임에 대해 알 필요가 있음

django로 백엔드만 구현을 하는 경우, render 나 HttpResponse 말고 서버에서 처리된 데이터를 json 형태로 클라이언트로 보내주게 되는데 이때 JsonResponse를 사용함

아래 코드는 카테고리 모델에서 전체 카테고리 데이터를 불러와 JsonResponse 함수를 통해 데이터를 보내주는 내용임

from django.http import JsonResponse

def categories(request):
    all_categories = Category.objects.all()
    return JsonResponse(
        {
            "categories" : all_categories
        }
    )

하지만 이렇게 하면 에러 페이지가 출력이 됨.

그 이유는 all_categories 는 QuerySet 형태라 Serializer를 통해서 Json 형태로 바꿔줘야 하기 때문임

 

그러한 이유로 serializer 함수를 불러와 형태를 변환해주는 작업을 거쳐야 함.

from django.http import JsonResponse
from django.core import serializers


def categories(request):
    all_categories = Category.objects.all()
    return JsonResponse(
        {
            "categories" : serializers.serialize("json", all_categories) 
        }
    )

 

 

댓글