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)
}
)
'개발하면서적는글' 카테고리의 다른 글
[통계]부동산 분석을 위한 데이터 원천 (1) | 2024.01.04 |
---|---|
[통계] 검정력(power) (0) | 2023.02.06 |
노마드코더 에어비앤비 클론코딩 중간 후기(25% 완료) (0) | 2022.10.03 |
[django] 공통 칼럼 모델 작성 하기 (0) | 2022.10.03 |
[django] 에어비앤비 클론코딩 모델 복습 1 (0) | 2022.10.01 |
댓글