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

Room Booking Payloads

mediumDjango REST FrameworkDRF Serializers—No data yet

Problem statement

In this Django project, rebuild the hotel's payload layer: the booking serializer and the availability query. The booking serializer is a hand-typed copy of the Booking table that has been drifting since the day it was written, with a column missing, two bounds that disagree with the column they claim to mirror, no defence against a client posting the values the server owns, and a taken reference that comes back as a database exception instead of a message on a field. It carries no rules either, so a stay that started last March, a stay that ends before it begins and a party of forty in a room that sleeps two are all accepted and stored. Beside it the availability query declares no fields at all and therefore accepts every question ever asked of it.

Requirements

Implement:

  • BookingSerializer and AvailabilityQuerySerializer in app/serializers.py

Only that file changes, and both classes keep those names: they are what the tests import. app/models.py (read-only) holds Room and Booking, and is the only description of a booking in this project:

FieldColumnWho provides it
idBigAutoField primary keythe database
roomForeignKey(Room)the client, as the room's id
referenceCharField(max_length=10, unique=True)the client
guest_nameCharField(max_length=60)the client
starts_onDateFieldthe client
ends_onDateFieldthe client
guest_countIntegerField, so the column itself takes any whole number, negatives includedthe client
nightly_rateDecimalField(max_digits=7, decimal_places=2)the client
guest_noteTextField(blank=True)the client, and no reader ever sees it
staff_noteTextField(blank=True)hotel staff, and the payload never carries it at all
created_atDateTimeField(auto_now_add=True)the database, on the first write
confirmation_codeCharField(max_length=24)Booking.save(), which sets it to CONF- followed by the upper-cased reference, on every write

Room holds name (CharField(max_length=40)) and capacity (IntegerField), and capacity is how many guests the room sleeps. There are no routes and no views in this project: the payload layer is the whole surface, and the tests drive it directly with BookingSerializer(booking) to read, BookingSerializer(data=...) to write, and AvailabilityQuerySerializer(data=...) to check an availability question.

1. The booking payload, derived from the model

  • BookingSerializer is a ModelSerializer over Booking, configured in an inner Meta.
  • Nothing in it restates a length, a precision or a uniqueness rule that Booking already states, so an 11-character reference, a 61-character guest_name, a nightly_rate with three decimal places and a nightly_rate with more than seven digits are each refused by is_valid() with the offending field named in errors.

2. The exact field set

  • Meta.fields is an explicit list of field names, not "__all__".
  • Reading a booking back returns exactly id, room, reference, guest_name, starts_on, ends_on, guest_count, nightly_rate, created_at and confirmation_code, and nothing else.
  • Each value carries the type the table promises: id, room and guest_count as numbers, room as the room's id, reference as a string, the two dates as YYYY-MM-DD, and nightly_rate as a quoted two-place decimal, so a rate of 120 goes out as the string "120.00".
  • staff_note is staff-only: it is not in the list, so it is neither rendered nor settable, and a body that carries it is ignored rather than refused.
  • many=True renders a list, one item per row, in the order the queryset handed them over; nothing re-sorts it for you.

3. The values the server owns

  • id, created_at and confirmation_code are read-only.
  • Each one appears in the output, so a reader sees the id, the creation time and a confirmation_code built from the reference.
  • A client that posts its own value for any of them has that value discarded rather than obeyed or refused: it does not reach validated_data, and the stored booking carries the server's value. This holds on a create and on an update alike.

4. The note nobody reads back

  • guest_note is write-only: a client sends it, it reaches validated_data and it is stored, and it never appears in the output of a read.

5. The reference somebody already has

  • A payload whose reference is already stored fails is_valid() with an error under the reference key, and never reaches the database, because by then the only answer left is an exception.
  • A booking that keeps its own reference on an update is not colliding with anything and still validates.

6. The rules that belong to one field

  • A starts_on that is not in the future is invalid, so today and yesterday are both refused, with this message: ``text A booking must start on a future date. ``
  • That error lands under the starts_on key and brings no non_field_errors with it, because it is a rule one field can be judged against on its own. Tomorrow is accepted.
  • A party of fewer than 1 or more than 8 guests is invalid, so 1 and 8 pass and 0, -1, 9 and 40 do not, with this message: ``text Guests must be between 1 and 8. ``
  • Write that rule once, as a reusable validator, and attach it to guest_count here and to the availability query's guests field in requirement 7. Two copies of the same check is the thing this requirement exists to avoid. Its error lands under the key of the field that broke it.

7. The availability query

  • AvailabilityQuerySerializer is a plain serializers.Serializer: an availability question is answered rather than stored, so there is no model to derive it from and no save() to write.
  • It declares exactly four required fields:
KeyType
room_namestring
from_datedate
to_datedate
guestsinteger, judged by the reusable guest rule from requirement 6
  • A valid question exposes all four in validated_data, typed: the two dates as real date objects and guests as a real int.
  • A question missing a key, or carrying a value of the wrong type, reports that key and only that key in errors.

8. The rules about two values together

  • An ends_on that is not later than starts_on is invalid, so an end before the start and an end exactly on the start are both refused, with this message: ``text A booking must end after it starts. ``
  • A guest_count larger than the capacity of the booked room is invalid, with this message: ``text The guest count exceeds the room capacity. ``
  • Both land under the non_field_errors key, because no single value is wrong by itself: each rule is about two of them together.
  • On a partial update each side of those rules takes the value the body supplies, or, when the body leaves it out, the value the booking already has on file. A body carrying only ends_on is judged against the stored starts_on, and a body carrying only guest_count against the stored room.
  • On a create there is no stored booking to read from, so a missing value is reported by its own required check and the pair rules stay out of it.

9. Saving, and partial updates

  • A validated booking payload saves in both directions: save() with no instance writes a new booking and returns it, and save() with an instance changes that booking, adds none, leaves every other booking alone and returns it.
  • A serializer built with partial=True asks nothing of the fields the body leaves out, so an omitted field skips its required check while a full body still reports it.
  • Every rule above still runs for the fields a partial body does supply.

Notes

  • ModelSerializer builds its fields by inspecting the model, so a column's type, length, precision and uniqueness arrive without being retyped. A retyped limit is the next thing to go stale.
  • read_only_fields in Meta names values the server owns, and extra_kwargs passes keyword arguments to a generated field, which is how one becomes write_only without being retyped by hand.
  • A ForeignKey becomes a field that takes the related row's id on input and renders that id on output, while validated_data holds the related object itself.
  • A validate_<field> method judges one field and reports under its key; a plain callable in a field's validators list is the same rule shared by several fields; validate(attrs) runs once after every field and its error lands under non_field_errors. Return the value, and the whole dict, or what you validated is dropped on the way out.
  • A field with no required=False and no default is required, so a missing key reports itself under its own name.
  • Do not add a field the model does not have, and do not expose one the field list leaves out.
  • This project has no routes, so do not reach for an APIView, a ViewSet, a router, a generic view, a permission class or an authentication class: the payload layer is the whole answer.
  • Nothing outside requirements.txt is available.

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 yetmediumSerializer Validation RulesAppointments that start in the past or end before they start reach the clinic's database because the serializer only checks types, and a partial edit is waved through unchecked. Layer the field rule, the cross-field rule and one shared count rule onto the serializer so every submitted value is judged, whether the update is whole or partial.—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.