Skip to main content

DRF Serializers

Serializerโ€‹

์ง๋ ฌํ™”(serializer)์™€ ์—ญ์ง๋ ฌํ™”(deserialize) ๊ธฐ๋Šฅ์„ ๋™์‹œ์— ๊ฐ–๊ณ  ์žˆ๋Š” DRF์˜ ๊ธฐ๋Šฅ์ด๋‹ค. ํด๋ผ์ด์–ธํŠธ์™€ ์„œ๋ฒ„ API ๊ฐ„ ๋ฐ์ดํ„ฐ ์–‘์‹์„ ๋งž์ถฐ์ฃผ๋Š” ๋ณ€ํ™˜๊ธฐ๋ผ๊ณ  ์ƒ๊ฐํ•˜๋ฉด ๋œ๋‹ค. serializer๋Š” python object๋ฅผ JSON ๊ฐ™์€ ๋ฐ์ดํ„ฐ ํฌ๋งท์œผ๋กœ ๋ณ€ํ™˜ํ•˜๋Š” ๊ฑฐ๊ณ , deserializer๋Š” JSON ๋ฐ์ดํ„ฐ๋ฅผ python object๋กœ ๋ณ€ํ™˜ํ•˜๋Š” ๊ฒƒ์„ ์˜๋ฏธํ•œ๋‹ค. DRF์˜ Serializer๋Š” ์ด๋Ÿฐ ์ž‘์—…์„ ์ž๋™์œผ๋กœ ์ฒ˜๋ฆฌํ•ด์ค˜์„œ API ๊ฐœ๋ฐœ์„ ์‰ฝ๊ฒŒ ๋งŒ๋“ค์–ด์ค€๋‹ค.

๊ฐ„๋‹จ ์‚ฌ์šฉ๋ฒ•โ€‹

model ์ •์˜โ€‹

๋จผ์ € models.py๋ฅผ ๋งŒ๋“ค์–ด Django ๋ชจ๋ธ์„ ์ •์˜ํ•œ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด Book ๋ชจ๋ธ์„ ์ •์˜ํ•ด๋ณธ๋‹ค.

from django.db import models  

class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=100)
published_date = models.DateField()
isbn = models.CharField(max_length=13)

Serializer ์ •์˜โ€‹

๋‹ค์Œ์œผ๋กœ serializers.py๋ฅผ ๋งŒ๋“ค๊ณ  serializer๋ฅผ ์ •์˜ํ•œ๋‹ค.

from rest_framework import serializers  
from .models import Book

class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = ['id', 'title', 'author', 'published_date', 'isbn']

Serializer ํ™œ์šฉโ€‹

์ด๋ฒˆ์—๋Š” Serializer ์ธ์Šคํ„ด์Šค๋ฅผ ์ƒ์„ฑํ•˜๊ณ  ๋ฐ์ดํ„ฐ๋ฅผ ์ง๋ ฌํ™”ํ•ด๋ณธ๋‹ค. views.py์— ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•œ๋‹ค.

from rest_framework.decorators import api_view  
from rest_framework.response import Response
from .models import Book
from .serializers import BookSerializer

@api_view(['GET'])
def get_book(request, pk):
try:
book = Book.objects.get(pk=pk)
except Book.DoesNotExist:
return Response(status=404)

serializer = BookSerializer(book)
return Response(serializer.data)

์œ„์˜ ์ฝ”๋“œ์—์„œ get_book์€ Book model ์ธ์Šคํ„ด์Šค๋ฅผ JSON์œผ๋กœ ๋ณ€ํ™˜ํ•˜์—ฌ ํด๋ผ์ด์–ธํŠธ์— ๋ฐ˜ํ™˜ํ•œ๋‹ค.

๋‹ค์Œ์œผ๋กœ ์—ญ์ง๋ ฌํ™”๋ฅผ ํ•ด๋ณธ๋‹ค. POST๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ํด๋ผ์ด์–ธํŠธ๋กœ๋ถ€ํ„ฐ ๋ฐ›์€ JSON ๋ฐ์ดํ„ฐ๋ฅผ Python object๋กœ ๋ณ€ํ™˜ํ•  ์ˆ˜ ์žˆ๋‹ค.

@api_view(['POST'])  
def create_book(request):
serializer = BookSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=201)
return Response(serializer.errors, status=400)

์œ„์˜ ์ฝ”๋“œ์—์„œ create_book์€ ํด๋ผ์ด์–ธํŠธ๋กœ๋ถ€ํ„ฐ ๋ฐ›์€ JSON ๋ฐ์ดํ„ฐ๋ฅผ Book ์ธ์Šคํ„ด์Šค๋กœ ๋ณ€ํ™˜ํ•˜๊ณ  ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์— ์ €์žฅํ•œ๋‹ค.

๐ŸŒ Referencesโ€‹