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:
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',)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With