Nick Nick - 26 days ago 8
reST (reStructuredText) Question

Django REST Serializer Method Writable Field

I'm reading up on Django REST Framework and I have a model that is serialized with getters using the SerializerMethodField().

However, when I POST to this endpoint, I want to be able to set this field as well, but that doesn't work because, as the docs show above, you can't write to a SerializerMethodField. Is there any way in Django REST to have a serializer field that you define a custom getter method for, and a custom setter method?

EDIT: Here's the source of what I'm trying to do. Client has a 1-to-1 relationship with User.

class ClientSerializer(serializers.ModelSerializer):
email = serializers.SerializerMethodField()

def create(self, validated_data):
email = validated_data.get("email", None) # This doesn't work because email isn't passed into validated_data because it's a readonly field
# create the client and associated user here


def get_email(self, obj):
return obj.user.email

class Meta:
model = Client
fields = (
"id",
"email",
)

Answer

You need to use another type of field:

class ClientSerializer(serializers.ModelSerializer):
    email = serializers.EmailField(source='user.email')

    def create(self, validated_data):
        # DRF will create object {"user": {"email": "inputed_value"}} in validated_date
        email = validated_data.get("user", {}).get('email')

    class Meta:
        model = Client
        fields = (
            "id",
            "email",
        )