Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems to serialize property (getter and setter) from a model using Django Rest Framework

I want to use a property (including setter) from my model in a Serializer, but apparently, the setter is never called.

models.py

class Awesome(models.Model):
    _value = models.TextField()
    def set_value(self, value):
        self._value = value
    def get_value(self):
        return self._value
    value = property(get_value, set_value)

serializers.py

class AwesomeSerializer(serializers.ModelSerializer):
    class Meta:
        model = Awesome
        fields = ('value',)

views.py

class AwesometViewSet(viewsets.ModelViewSet):
    queryset = Awesome.objects.all()
    serializer_class = AwesomeSerializer

On this scenario suggested above, when I make a GET the getter work fine, but when I make a POST the serializer doesn't call the setter.

What wrong I made?!

I am using following versions:

  • python == 3.6.1
  • Django == 1.11.2
  • djangorestframework == 3.6.3
like image 698
Rodrigo Braga Avatar asked Jun 22 '17 15:06

Rodrigo Braga


1 Answers

You are using ModelSerializer which automatically creates read-write fields on the serializer based on the fields on the model. When it is not a field (a property or a method) and declared in Meta.fields, it defaults to a read only field.

Declaring it explicitly on the serializer will make it a RW field:

class AwesomeSerializer(serializers.ModelSerializer):
    value = serializers.CharField()
    class Meta:
        model = Awesome
        fields = ('value',)
like image 180
Michael Rigoni Avatar answered Oct 13 '22 01:10

Michael Rigoni