TIL day-55

yo·2020년 8월 13일
0

Serialzer정의
Serializers allow complex data such as querysets and model instances to be converted to native Python data types that can then be easily rendered into userful formats like JSON: this process is known as Serialization of Data.

Serializers are a very important component of DRF, that we can easily use by employing the Serializer and ModelSerializer classes.

Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.

  • models.py의 TextField는 serializers.py에선 serializers.CharField()로 쓰면 된다.

serializer 실습

from news.models import Article
from news.api.serializers import ArticleSerializer
from rest_framework.renderers import JSONRenderer
import io
from rest_framework.parsers import JSONParser

>>> article_instance = Article.objects.first()
>>> serializer = ArticleSerializer(article_instance)
>>> serializer.data
{'id': 1, 'author': 'KIm', 'title': 'how i met your mother', 'description': 'fun story', 'body': 'some body', 'location': 'Seoul', 'publication_date': '2020-07-29', 'active': True, 'created_at': '2020-07-29T08:19:56.092979Z', 'updated_at': '2020-07-29T08:19:56.093002Z'}

>>> json = JSONRenderer().render(s.data)
>>> json
b'{"id":1,"author":"KIm","title":"how i met your mother","description":"fun story","body":"some body","location":"Seoul","publication_date":"2020-07-29","active":true,"created_at":"2020-07-29T08:19:56.092979Z","updated_at":"2020-07-29T08:19:56.093002Z"}'

>>> stream = io.BytesIO(json)
>>> data = JSONParser().parse(stream)
>>> data
{'id': 1, 'author': 'KIm', 'title': 'how i met your mother', 'description': 'fun story', 'body': 'some body', 'location': 'Seoul', 'publication_date': '2020-07-29', 'active': True, 'created_at': '2020-07-29T08:19:56.092979Z', 'updated_at': '2020-07-29T08:19:56.093002Z'}
>>>

>>> serializer = ArticleSerializer(data=data)
>>> serializer.is_valid()
True
>>> serializer.validated_data
OrderedDict([('author', 'KIm'), ('title', 'how i met your mother'), ('description', 'fun story'), ('body', 'some body'), ('location', 'Seoul'), ('publication_date', datetime.date(2020, 7, 29)), ('active', True)])
>>> serializer.save()
{'author': 'KIm', 'title': 'how i met your mother', 'description': 'fun story', 'body': 'some body', 'location': 'Seoul', 'publication_date': datetime.date(2020, 7, 29), 'active': True}
<Article: KIm how i met your mother>

#api_view decorator를 활용하여 read&write가능한 api만들기

DRF's APIView class사용하기

profile
Never stop asking why

0개의 댓글