matteok
matteok

Reputation: 2189

create multiple objects using writable nested serializers in django rest framework 3

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?

Upvotes: 6

Views: 3026

Answers (1)

matteok
matteok

Reputation: 2189

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

Upvotes: 7

Related Questions