Create multiple objects using rewritable nested serializers in django rest framework 3

In drf3, you can now implement a writable nested serializer by overriding the create () method and independently processing validated_data p>

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 to do if the profile was a multi- profile, and validated_data actually contains several profiles . How to create multiple related objects in create?

+5
source share
1 answer

As suggested by krs, the answer is:

 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 
+5
source

Source: https://habr.com/ru/post/1208222/


All Articles