0
votes

I'm using Django rest framework 3.7.7

I want to serialize an object instance and then deserialize it (without saving to DB again). So I created a serializer that inherits from serializers.ModelSerializer. To this model instance I sometimes add a field within the request that is not part of the model, using property setter. I did add it to the serializer as well, but when serializing - I don't see that field in the serialized data.

This is the model:

class MyModel(models.Model):

    manager = models.CharField(max_length=200)
    reviewer = models.CharField(max_length=200)

    @property
    def note(self):
        return getattr(self, '_note', None)

    @note.setter
    def note(self, value):
        self._note = value

This is the model serializer:

class MyModelSerializer(serializers.ModelSerializer):
    note = serializers.CharField(write_only=True, required=False, max_length=1000, allow_null=True)

    class Meta:
        model = MyModel
        fields = [
            'manager',
            'reviewer',
            'note'
        ]

This is how I use the serializer:

ser_instance = MyModelSerializer(self.instance)
ser_data = ser_instance.data

seems like the ser_instance.data contains only the model fields data (without the 'note')

1

1 Answers

0
votes

From the write_only--[DRF-Doc], it states that

Set this to True to ensure that the field may be used when updating or creating an instance, but is not included when serializing the representation.

Defaults to False


So, if you need to serialize the note field, remove the write_only=true from serializer.

#serializers.py
class MyModelSerializer(serializers.ModelSerializer):
    note = serializers.CharField(required=False, max_length=1000, allow_null=True)  # removed "write_only=True"
    ...