Search code examples
pythondjangodjango-rest-frameworkdjango-serializer

How to add custom field in ModelSerializer?


I created a ModelSerializer and want to add a custom field which is not part of my model.

I found a description to add extra fields here and I tried the following:

customField = CharField(source='my_field')

When I add this field and call my validate() function then this field is not part of the attr dict. attr contains all model fields specified except the extra fields. So I cannot access this field in my overwritten validation, can I?

When I add this field to the field list like this:

class Meta:
    model = Account
    fields = ('myfield1', 'myfield2', 'customField')

then I get an error because customField is not part of my model - what is correct because I want to add it just for this serializer.

Is there any way to add a custom field?


Solution

  • 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')