Django Rest Framework How to update SerializerMethodField

对着背影说爱祢 提交于 2020-05-12 11:49:11

问题


I have a serializer like this:

class PersonSerializer(serializers.ModelSerializer):
    gender = serializers.SerializerMethodField()
    bio = BioSerializer()

    class Meta:
        model = Person
        fields = UserSerializer.Meta.fields + ('gender', 'bio',)

    def get_gender(self, obj):
        return obj.get_gender_display()

I used this to display "Male" and "Female"(insted of "M" of "F") while performing GET request.

This works fine.

But now I am writing an patch method for the model and SerializerMethodField() has read_only=True. So I am not getting value passed for gender field in serializer.validated_data(). How to overcome this issue?


回答1:


So if I understand you correctly, you want to send {'gender': 'Male'} in your PATCH request.

Therefor, you have to tell your serializer how to convert your representation i.e. 'Male' into the internal value.

As you can see in source, SerializerMethodField only covers the conversion from internal value to the representation.

You can implement a custom SerializerField that performs the necessary conversions. A naive implementation could something like this:

class GenderSerializer(serializers.Field):

    VALUE_MAP = {
        'M': 'Male',
        'F': 'Female'
    }

    def to_representation(self, obj):
        return self.VALUE_MAP[obj]            

    def to_internal_value(self, data):
        return {k:v for v,k in self.VALUE_MAP.items()}[data]

class PersonSerializer(serializers.ModelSerializer):
    gender = GenderSerializer()
    ...

Note that this untested and lacks any validation, check out the DRF docs on custom fields.



来源:https://stackoverflow.com/questions/37475829/django-rest-framework-how-to-update-serializermethodfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!