Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 580
matteok Avatar asked Dec 03 '14 11:12

matteok


1 Answers

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
like image 110
matteok Avatar answered Nov 03 '22 10:11

matteok