Using Super create method for ModelSerializer

Nate Parke picture Nate Parke · Nov 11, 2015 · Viewed 7.3k times · Source

I am trying to save some work by using the create method of the ModelSerializer in an extension of the class and then adding in the extra fields that I need in the extension. When I do this however I get an error from DRF about not supporting writable fields in nested serializers. Is there some way to implement this so that I don't have to explicitly define each field in the create method and instead push that work onto the super constructor? Included is my code:

class CreateUserSerializer(ModelSerializer):
    school = SchoolSerializer(required=False) 

    class Meta:
        model = User
        fields = ('id', 'username', 'password', 'first_name', 'last_name',
              'user_type', 'school', 'email')
        extra_kwargs = {
            'password': {'write_only': True},
            'user_type': {'read_only': True}
        }

    def create(self, validated_data):
        original_validated_data = validated_data.copy()
        if 'password' in validated_data:
            password = validated_data.pop('password')

        user = super(CreateUserSerializer, self).create(validated_data)
        if 'password' in original_validated_data:
            user.set_password(original_validated_data['password'])
        if 'school' in original_validated_data:
            user.user_type = User.TYPE_ADVISOR

        return user

And this is the error that I am getting:

File "/serializers/user.py", line 41, in create
  user = super(CreateUserSerializer, self).create(validated_data)
File "/lib/python2.7/site-packages/rest_framework/serializers.py", line 832, in create
  raise_errors_on_nested_writes('create', self, validated_data)
File "/lib/python2.7/site-packages/rest_framework/serializers.py", line 724, in raise_errors_on_nested_writes
  class_name=serializer.__class__.__name__
AssertionError: The `.create()` method does not support writable nestedfields by default.
Write an explicit `.create()` method for serializer `api.serializers.user.CreateUserSerializer`, or set `read_only=True` on nested serializer fields.

I am using Rest Framework V3.3.1

Answer

Niels van Eldik picture Niels van Eldik · Nov 11, 2015

I don't think that will work, as calling super effectively means you are calling the base method which according to the documentation does not support writing nested models.

To solve this have a look at:

http://www.django-rest-framework.org/api-guide/relations/#writable-nested-serializers