Django Rest Framework How to update SerializerMethodField

前端 未结 2 373
野性不改
野性不改 2021-01-07 23:43

I have a serializer like this:

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


        
相关标签:
2条回答
  • 2021-01-08 00:14

    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 GenderSerializerField(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 = GenderSerializerField()
        ...
    

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

    0 讨论(0)
  • 2021-01-08 00:20

    Aside from accepted answer, there can be other simpler hooks. If 'create' and 'update' worked as you wanted before modifiying gender field, then you can do as follow to get everything to default for create and update requests.

    • Override the __init__ method . .
    class PersonSerializer(serializers.ModelSerializer):
        bio = BioSerializer()
        
         def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
    
            try:
                if self.context['request'].method in ['GET']:
                    self.fields['gender'] = serializers.SerializerMethodField()
            except KeyError:
                pass
    
        class Meta:
            model = Person
            fields = UserSerializer.Meta.fields + ('bio',)
    
        def get_gender(self, obj):
            return obj.get_gender_display()   
           
    ...
    
    0 讨论(0)
提交回复
热议问题