0
votes

How can I create a custom Serializer Field that returns a value different from the value saved to the database?

For example:

  • Database currently has the value ['alpha', 'bravo', 'delta']
  • It's updated with the value ['alpha', 'delta', 'E']
  • Field should save ['alpha', 'delta', 'echo'] to the database and run a delete function on 'bravo'
  • Field should return ['alpha', 'delta', {'foo': 'E', 'bar': 'echo'}] in the 201 response (but not in 200 responses)

Essentially, I'm looking for a method in the custom Field I can write my logic with two inputs (from request and from database) and two outputs (to database and to Response)

1

1 Answers

0
votes

You should check DRF documentation on custom fields

As stated, to return a custom object, you have to define the .to_representation() method.

The example from the docs:

class ClassNameField(serializers.Field):
    def get_attribute(self, obj):
        # We pass the object instance onto `to_representation`,
        # not just the field attribute.
        return obj

    def to_representation(self, obj):
        """
        Serialize the object's class name.
        """
        return obj.__class__.__name__