Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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",
        )
like image 435
Nick Avatar asked Nov 11 '16 20:11

Nick


5 Answers

Here is a read/write serializer method field:

class ReadWriteSerializerMethodField(serializers.SerializerMethodField):
    def __init__(self, method_name=None, **kwargs):
        self.method_name = method_name
        kwargs['source'] = '*'
        super(serializers.SerializerMethodField, self).__init__(**kwargs)

    def to_internal_value(self, data):
        return {self.field_name: data}

like image 145
Julio Marins Avatar answered Sep 30 '22 04:09

Julio Marins


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",
        )
like image 20
zymud Avatar answered Oct 02 '22 04:10

zymud


I tried to use Guilherme Nakayama da Silva and Julio Marins's answers to fix my problem with writing to a SerializerMethodField. It worked for reading and updating, but not for creating.

So I created my own WritableSerializerMethodField based on their answers, it works perfectly for reading, creating and writing.

class WritableSerializerMethodField(serializers.SerializerMethodField):
    def __init__(self, **kwargs):
        self.setter_method_name = kwargs.pop('setter_method_name', None)
        self.deserializer_field = kwargs.pop('deserializer_field')

        super().__init__(**kwargs)

        self.read_only = False

    def bind(self, field_name, parent):
        retval = super().bind(field_name, parent)
        if not self.setter_method_name:
            self.setter_method_name = f'set_{field_name}'

        return retval

    def get_default(self):
        default = super().get_default()

        return {
            self.field_name: default
        }

    def to_internal_value(self, data):
        value = self.deserializer_field.to_internal_value(data)
        method = getattr(self.parent, self.setter_method_name)
        return {self.field_name: self.deserializer_field.to_internal_value(method(value))}

Then I used this in my serializer

class ProjectSerializer(serializers.ModelSerializer):
    contract_price = WritableSerializerMethodField(deserializer_field=serializers.DecimalField(max_digits=12, decimal_places=2))

    def get_contract_price(self, project):
        return project.contract_price

    def set_contract_price(self, value):
        return value
like image 36
Dylan Larsen Avatar answered Oct 01 '22 04:10

Dylan Larsen


In my case, I needed the logic inside my get_* method and couldn't fetch the value using the source attribute. So I came up with this field.

class WritableSerializerMethodField(serializers.SerializerMethodField):
    def __init__(self, method_name=None, **kwargs):
        super().__init__(**kwargs)

        self.read_only = False

    def get_default(self):
        default = super().get_default()

        return {
            self.field_name: default
        }

    def to_internal_value(self, data):
        return {self.field_name: data}
like image 27
Guilherme Nakayama da Silva Avatar answered Sep 30 '22 04:09

Guilherme Nakayama da Silva


You can override the save() method on the serializer and use self.initial_data. You'll then need to do the validation on that field yourself though.

class MySerializer(serializers.ModelSerializer):

    magic_field = serializers.SerializerMethodField()

    def get_magic_field(self, instance):
        return instance.get_magic_value()

    def save(self, **kwargs):

        super().save(**kwargs)  # This creates/updates `self.instance`

        if 'magic_field' in self.initial_data:
            self.instance.update_magic_value(self.initial_data['magic_field'])

        return self.instance
like image 35
gitaarik Avatar answered Oct 03 '22 04:10

gitaarik