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 using source="host.name".

  • duration_seconds: Required, must be at least 1.

  • level: Must be one of beginner, intermediate, or advanced.

  • token: Write-only input field mapped to the model's secret_token field.

  • is_long_title: Read-only computed field using SerializerMethodField. Returns true if 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:

  1. What is the recommended way to map an input field named token to a model field named secret_token without exposing it in the response?

  2. Should I use validate_title() or override another serializer method for whitespace validation?

  3. What is the correct approach to implement is_long_title using SerializerMethodField?

  4. How can I handle empty PUT and PATCH requests consistently and return a custom error under non_field_errors?

  5. 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.

Вернуться на верх