TIL day-49

yo·2020년 7월 29일
0

DRF serializer 실습

설정
1)pip install djangorestframework
2)settings.py의 installed apps에 'rest_framework' 추가

models.py

serializers.py

>>> from map.models import Subway
>>> from map.api.serializers import SubwaySerializer
>>> from rest_framework.renderers import JSONRenderer
>>> from rest_framework.parsers import JSONParser
>>> import io

>>> subway_instance = Subway.objects.first()
>>> subway_instance
<Subway: Subway object (1)>

>>> serializer = SubwaySerializer(subway_instance)
>>> serializer
SubwaySerializer(<Subway: Subway object (1)>):
    id = IntegerField(read_only=True)
    subway_code = IntegerField()
    name = CharField()
    longitude = DecimalField(18, 15)
    latitude = DecimalField(18, 15)
    local = CharField()
    
>>> dic = serializer.data
>>> dic
{'id': 1, 'subway_code': 1, 'name': '서울역', 'longitude': '37.555728912353500', 'latitude': '126.972145080566000', 'local': '서울특별시'}

>>> json = JSONRenderer().render(serializer.data)
>>> json
b'{"id":1,"subway_code":1,"name":"\xec\x84\x9c\xec\x9a\xb8\xec\x97\xad","longitude":"37.555728912353500","latitude":"126.972145080566000","local":"\xec\x84\x9c\xec\x9a\xb8\xed\x8a\xb9\xeb\xb3\x84\xec\x8b\x9c"}'
>>> stream = io.BytesIO(json)
>>> data = JSONParser().parse(stream)
>>> data
{'id': 1, 'subway_code': 1, 'name': '서울역', 'longitude': '37.555728912353500', 'latitude': '126.972145080566000', 'local': '서울특별시'}

>>> serializer = SubwaySerializer(data=data)

>>> serializer.is_valid()
True

>>> serializer.validated_data
OrderedDict([('subway_code', 1), ('name', '서울역'), ('longitude', Decimal('37.555728912353500')), ('latitude', Decimal('126.972145080566000')), ('local', '서울특별시')])

>>> serializer.save()
{'subway_code': 1, 'name': '서울역', 'longitude': Decimal('37.555728912353500'), 'latitude': Decimal('126.972145080566000'), 'local': '서울특별시'}
<Subway: Subway object (885)>
>>>
profile
Never stop asking why

0개의 댓글