Django Rest Framework - How to add custom field in ModelSerializer Django Rest Framework - How to add custom field in ModelSerializer python python

Django Rest Framework - How to add custom field in ModelSerializer


In fact there a solution without touching at all the model. You can use SerializerMethodField which allow you to plug any method to your serializer.

class FooSerializer(ModelSerializer):    foo = serializers.SerializerMethodField()    def get_foo(self, obj):        return "Foo id: %i" % obj.pk


You're doing the right thing, except that CharField (and the other typed fields) are for writable fields.

In this case you just want a simple read-only field, so instead just use:

customField = Field(source='get_absolute_url')


...for clarity, if you have a Model Method defined in the following way:

class MyModel(models.Model):    ...    def model_method(self):        return "some_calculated_result"

You can add the result of calling said method to your serializer like so:

class MyModelSerializer(serializers.ModelSerializer):    model_method_field = serializers.CharField(source='model_method')

p.s. Since the custom field isn't really a field in your model, you'll usually want to make it read-only, like so:

class Meta:    model = MyModel    read_only_fields = (        'model_method_field',        )