Django Rest Framework를 장고 프로젝트에 설정할 수 있어야한다!
class Toy(models.Model):
created = models.DateTimeField(auto_now_add=True)
name = models.CharField(max_length=150, blank=False, default='')
description = models.CharField(max_length=250, blank=True, default='')
toy_category = models.CharField(max_length=200, blank=False, default='')
release_date = models.DateTimeField()
was_included_in_home = models.BooleanField(default=False)
class Meta:
ordering = ('name',)
from rest_framework import serializers
from toys.models import Toy
class ToySerializer(serializers.Serializer):
pk = serializers.IntegerField(read_only=True)
name = serializers.CharField(max_length=150)
description = serializers.CharField(max_length=250)
release_date = serializers.DateTimeField()
toy_category = serializers.CharField(max_length=200)
was_included_in_home = serializers.BooleanField(required=False)
def create(self, validated_data):
return Toy.objects.create(**validated_data)
def update(self, instance, validated_data):
instance.name = validated_data.get('name', instance.name)
instance.description = validated_data.get('description', instance.description)
instance.release_date = validated_data.get('release_date', instance.release_date)
instance.toy_category = validated_data.get('toy_category', instance.toy_category)
instance.was_included_in_home = validated_data.get('was_included_in_home', instance.was_included_in_home)
instance.save()
return instance
python manage.py shell
지금 부터 파이썬 쉘에 한줄 한줄 입력해야한다...
from datetime import datetime
from django.utils import timezone
from io import BytesIO
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from toys.models import Toy
from toys.serializers import ToySerializer
toy_release_date = timezone.make_aware(datetime.now(), timezone.get_current_timezone())
toy1 = Toy(name='Snoopy talking action figure',
description='Snoopy speaks five languages',
release_date=toy_release_date,
toy_category='Action figures',
was_included_in_home=False)
toy1.save()
print(toy1.pk)
print(toy1.name)
print(toy1.created)
print(toy1.was_included_in_home)
모델 객체를 파이썬 딕셔너리로 변환한다.
serializer_for_toy1 = ToySerializer(toy1)
print(serializer_for_toy1.data)
{
'pk': 1,
'name': 'Snoopy talking action figure',
'description': 'Snoopy speaks five languages',
'release_date': '2017-10-09T12:11:37.090335Z',
'toy_category': 'Action figures',
'was_included_in_home': False
}
JSONRenderer 의 render()
메서드는 위에서 만든 딕셔너리를 바이너리 JSON 형태로 변환해준다.
json_renderer = JSONRenderer()
toy1_rendered_into_json = json_renderer.render(serializer_for_toy1.data)
print(toy1_rendered_into_json)
b'{"pk":1,"name":"Snoopy talking action figure", "description": "Snoopy speaks five languages", "release_date": "2017-10-09T12:11:37.090335Z", "toy_category": "Action figures", "was_included_in_home": false}
JSON 문자열을 바이트 타입으로 바꾸고, ByteIO 객체로 바꾼다. JSONParser 의 parser()
메서드를 이용하여 딕셔너리 형태로 변환한다.
json_string_for_new_toy = '{"name":"Clash Royale play set","description":"6 figures from Clash Royale", "release_date":"2017-10-09T12:10:00.776594Z","toy_category":"Playset","was_included_in_home":false}'
json_bytes_for_new_toy = bytes(json_string_for_new_toy, encoding="UTF-8")
stream_for_new_toy = BytesIO(json_bytes_for_new_toy)
parser = JSONParser()
parsed_new_toy = parser.parse(stream_for_new_toy)
print(parsed_new_toy)
{
'name': 'Clash Royale play set',
'description': '6 figures from Clash Royale',
'release_date': '2017-10-09T12:10:00.776594Z',
'toy_category': 'Playset',
'was_included_in_home': False
}
위에서 만든 딕셔너리를 Serializer 객체를 이용해 Toy 객체로 변환하고 데이터베이스에 저장한다.
new_toy_serializer = ToySerializer(data=parsed_new_toy)
if new_toy_serializer.is_valid():
toy3 = new_toy_serializer.save()
quit()