In drf3 you can now implement a writable nested serializer by overriding the create() method and handling validated_data yourself
def create(self, validated_data):
profile_data = validated_data.pop('profile')
user = User.objects.create(**validated_data)
Profile.objects.create(user=user, **profile_data)
return user
What if profile was a to many relationship and the validated_data would actually contain multiple profiles. How would I create multiple related objects in create?
As suggested by krs the answer is the following:
def create(self, validated_data):
profiles_data = validated_data.pop('profiles')
user = User.objects.create(**validated_data)
for profile_data in profiles_data:
profile = Profile.objects.create(user=user,**profile_data)
return user
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With