StaffCoder
Django
DjangoDjango 5.2Python 3.13
18 modules · 72 challengesSign up
Module 16 · DRF Serializers

Serializer Validation Rules

mediumDjango REST FrameworkDRF Serializers—No data yet

Problem statement

In this Django project, implement the clinic's booking rules on the appointment serializer. Build the field rule, the cross-field rule and one shared count rule in AppointmentSerializer in app/serializers.py, so a start in the past, an end before its start and a party nobody can seat come back as errors instead of rows. Today the serializer checks types and nothing else, and a partial edit is waved through without a single rule being asked.

Requirements

Implement:

  • the validation rules on AppointmentSerializer in app/serializers.py

The following files are already implemented and provided: app/models.py, app/views.py and app/urls.py. Appointment holds patient_name (CharField(max_length=120)), starts_at and ends_at (both DateTimeField) and adult_count and child_count (both IntegerField, so the column itself takes any whole number, negatives included). AppointmentSerializer is already a ModelSerializer over all five fields plus id; keep Meta.fields as it is. Nothing is exposed over HTTP: the serializer is used directly, so whether a booking is refused is decided entirely inside it.

1. The start of an appointment

  • A starts_at earlier than the moment of validation is invalid, with this message:
An appointment cannot start in the past.
  • That error lands under the starts_at key of serializer.errors, never on the object as a whole, because it is a rule one field can be judged against on its own.

2. The pair of timestamps

  • An ends_at that is not later than starts_at is invalid, so an end before the start and an end exactly on the start are both refused, with this message:
An appointment must end after it starts.
  • That error lands under the non_field_errors key, because neither timestamp is wrong by itself: the rule is about the two of them together.

3. The number of people

  • adult_count and child_count are each valid from 0 to 8 inclusive, so 0 and 8 pass and -1 and 9 do not, with this message:
Count must be between 0 and 8.
  • Write the rule once and attach it to both fields. Two copies of the same check, one per field, is the thing this requirement exists to avoid.
  • The error lands under the key of the field that broke it, and a field inside the range carries no error even when the other one is out of it.

4. A partial update

  • A serializer built with partial=True asks nothing of the fields the body leaves out, so a body carrying one field is complete and the rest of the record stays as it is.
  • Every rule that belongs to a field the body does supply still runs, so a partial update cannot slip a past start or a count of 9 through.
  • The pair rule takes the side the body does not supply from the appointment already stored, so a partial update that moves only ends_at is judged against the stored starts_at and is refused when it lands before it.
  • On a create there is no stored appointment to read a missing timestamp from, so an absent starts_at or ends_at is reported by its own required check and the pair rule stays out of it.

Notes

  • The rules are yours to write. A ModelSerializer gives you the type of each field and the length of patient_name for free, and nothing else: 2026 in the past, an end before a start and a hundred children are all well-typed.
  • A field rule can be a validate_<field> method or a callable in the field's validators list, whichever you prefer. A rule about two fields has to run after both are in hand, which a single field's method cannot do.
  • Return the value from a validate_<field> method and the whole dict from validate, or the data you validated is dropped on the way out.
  • Do not reach for views, routers, generics, permissions or any package outside requirements.txt.

More in DRF Serializers

See the module
Serialized Product PayloadThe product endpoint used to hand-build its response dicts and pick fields out of the raw request body, so field types drifted between endpoints and malformed input reached the database. Declare one plain Serializer with typed, constrained fields, so instances render to the defined payload, input is refused field by field, and save routes to create or update.—No data yetmediumModel Backed SerializerA hand-typed serializer restates its model's fields, drifts out of step with the columns after every change, and lets a client overwrite the values the server owns. Derive it from the model instead, with an explicit field list, read-only server-managed values, a write-only cost, and the taken sku answered as a field error.—No data yetmediumRoom Booking PayloadsA room-booking service checks nothing a client sends it, so a stay in the past, a stay that ends before it begins, a party larger than the room sleeps and a reference somebody already has all reach the database or corrupt a booking on the way. Build the whole payload layer: a booking serializer derived from the model with an explicit field set, server-owned values, a write-only note, field and cross-field rules, and a plain serializer for the availability query.—No data yetmedium

We use cookies that are necessary to run Staffcoder, and optional analytics cookies to see which pages get used. Analytics stays off unless you accept. Read our Cookie Policy.