How to implement custom field mapping and validation in a Django REST Framework ModelSerializer?
Question:
I'm implementing an EpisodeSerializer using Django REST Framework and need help handling several serializer fields and validation rules.
My serializer should include the following fields:
id: Read-only.title: Required, readable and writable.host: Accepts the host ID as input and returns its ID as output.host_name: Read-only, retrieves the host's name usingsource="host.name".duration_seconds: Required, must be at least 1.level: Must be one ofbeginner,intermediate, oradvanced.token: Write-only input field mapped to the model'ssecret_tokenfield.is_long_title: Read-only computed field usingSerializerMethodField. Returnstrueif the title length is greater than 15.created_at: Read-only and automatically generated.
I also have two custom validation requirements:
1. Title validation
A title containing only whitespace characters should be rejected with exactly this error message:
Title cannot be blank.
2. Empty PUT/PATCH requests
If a PUT or PATCH request is sent with an empty request body, the API should return HTTP 400 with the following error under the non_field_errors key:
At least one field must be provided.
My questions:
What is the recommended way to map an input field named
tokento a model field namedsecret_tokenwithout exposing it in the response?Should I use
validate_title()or override another serializer method for whitespace validation?What is the correct approach to implement
is_long_titleusingSerializerMethodField?How can I handle empty PUT and PATCH requests consistently and return a custom error under
non_field_errors?Should these validations be implemented inside the serializer or the view?
I'd like to follow Django REST Framework best practices rather than putting unnecessary logic in the view.