web/django

Django serializer 활용하기

민사민서 2024. 5. 8. 00:31

https://www.django-rest-framework.org/api-guide/serializers/#serializers

 

Serializers - Django REST framework

 

www.django-rest-framework.org

 

class PostListView(APIView):
  def get(self, request):
    posts = Post.objects.all()
    contents = [{"id": post.id,
                 "title": post.title,
                 "content": post.content,
                 "created_at": post.created_at} for post in posts]
    return Response(contents, status=status.HTTP_200_OK)

// 이런 식으로 QuerySet이라는 클래스의 객체 형태로 반환된 posts 변수를 

// Reponse에 담기위해 하드코딩하기 번거로움 => Serializer를 활용해 데이터를 변환하자

 

post/serializers.py 생성

from rest_framework.serializers import ModelSerializer
from .models import Post

class PostSerializer(ModelSerializer):
  class Meta:
    model = Post
    fields = '__all__'

 

- model serializer 는 장고의 기본 serializer 클래스를 상속받은 클래스

- model 의 fields 를 자동으로 인식하여 어떻게 직렬화해야 하는지에 대한 정보를 인지

 

 class Meta?

어떤 모델을 변환할 것인지, 그 meta data를 serializer에게 알려주는 class

 

post/views.py 개선

from rest_framework.views import APIView
from rest_framework import status
from rest_framework.response import Response
from .models import Post
from .serializers import PostSerializer

class PostListView(APIView):
  def get(self, request):
    posts = Post.objects.all()
    serializer = PostSerializer(posts, many=True)
    return Response(serializer.data, status=status.HTTP_200_OK)
  
  def post(self, request):
    title = request.data.get('title')
    content = request.data.get('content')
    if not title or not content:
      return Response({"msg": "title and content are required"}, status=status.HTTP_400_BAD_REQUEST)
    post = Post.objects.create(title=title, content=content)
    serializer = PostSerializer(post)
    return Response(serializer.data, status=status.HTTP_201_CREATED)
  
class PostDetailView(APIView):
  def get(self, request, post_id):
    try:
      post = Post.objects.get(id=post_id)
    except:
      return Response({"msg": "Post not found"}, status=status.HTTP_404_NOT_FOUND)
    serializer = PostSerializer(post)
    return Response(serializer.data, status=status.HTTP_200_OK)
  
  def delete(self, request, post_id):
    try:
      post = Post.objects.get(id=post_id)
    except:
      return Response({"msg": "Post not found"}, status=status.HTTP_404_NOT_FOUND)
    post.delete()
    return Response(status=status.HTTP_204_NO_CONTENT)

 

PostSerializer에게 class object를 넘겨주면 serializer class object가 리턴되고, .data로 데이터 가져오면 됨