6

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?

3
  • If you know it actually contains the data you think you can just create them in a loop Commented Dec 3, 2014 at 11:43
  • could you provide an example? Commented Dec 3, 2014 at 11:47
  • 1
    i dont know how the data is given as i havent upgraded to 3 yet, but if it is a list then a normal for-loop would do the job Commented Dec 3, 2014 at 11:48

1 Answer 1

7

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.