https://www.django-rest-framework.org/api-guide/serializers/#serializers
json response를 받고 그 데이터를 바로 serialize해서 model instance를 생성가능하다.
== ORM
class UserProfile(models.Model):
id = models.AutoField(primary_key=True)
full_name = models.CharField(max_length=500)
last_login_at = models.DateTimeField(blank=True, null=True)
time_zone = models.CharField(max_length=100, blank=True, null=True)
class Meta:
managed = False
db_table = 'user_profile'
class UserAccount(models.Model):
user_profile = models.OneToOneField(UserProfile, on_delete=models.CASCADE, primary_key=True)
email = models.CharField(max_length=255)
password = models.CharField(max_length=255, blank=True, null=True)
resetpw_auth_number = models.IntegerField(blank=True, null=True)
created_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'user_account'
class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
model = UserProfile
fields = '__all__'
class UserAccountSerializer(serializers.ModelSerializer):
user_profile = UserProfileSerializer()
class Meta:
model = UserAccount
fields = '__all__'
def create(self, validated_data):
user_profile_data = validated_data.pop('user_profile')
profile = UserProfile.objects.create(**user_profile_data)
account = UserAccount.objects.create(user_profile=profile, **validated_data)
return account
serializers = UserAccountSerializer(data=data)
if serializers.is_valid():
print(repr(serializers))
serializers.create(serializers.validated_data)
else:
return HttpResponse(json.dumps(serializers.errors, ensure_ascii=True), status=404, content_type="application/json")
return JsonResponse(data, status=201)