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

Model Backed Serializer

mediumDjango REST FrameworkDRF Serializers—No data yet

Problem statement

In this Django project, derive the marketplace's listing serializer from its model instead of maintaining a hand-typed copy of the table. The copy was correct the day it was written and has been drifting since: a column was added to the model and never added here, two of the copied declarations disagree with the lengths and precision the database actually enforces, and nothing stops a client from posting the identifier and the timestamp the server sets for itself. A supplier who reuses another supplier's sku gets a database exception instead of a message on the field.

Requirements

Implement:

  • ListingSerializer in app/serializers.py

Only that file changes, and the class keeps the name ListingSerializer: it is what the tests import. app/models.py (read-only) holds Listing, the only description of a listing in this project:

FieldColumnWho provides it
idBigAutoField primary keythe database
titleCharField(max_length=60)the supplier
skuCharField(max_length=12, unique=True)the supplier
priceDecimalField(max_digits=7, decimal_places=2)the supplier
cost_priceDecimalField(max_digits=7, decimal_places=2)the supplier, and no reader ever sees it
internal_noteTextField(blank=True)marketplace staff, and the API never carries it at all
created_atDateTimeField(auto_now_add=True)the database, on the first write
reference_codeCharField(max_length=24)Listing.save(), which sets it to MKT- followed by the upper-cased sku, on every write

This project has no routes and no views: the serializer is the whole surface, and the tests drive it directly with ListingSerializer(instance) to read and ListingSerializer(data=...) to write.

1. Derived from the model

  • ListingSerializer is a serializers.ModelSerializer over Listing, configured in an inner Meta.
  • Nothing in it restates a length, a precision or a uniqueness rule that Listing already states.
  • A 61-character title, a 13-character sku, a price with three decimal places and a price with more than seven digits are each refused by is_valid() with the offending field named in errors, while a 60-character title, a 12-character sku, 38.50 and 99999.99 all pass.

2. The exact field set

  • Meta.fields is an explicit list of field names, not "__all__": naming them means a new column reaches the API when somebody decides it should and not before.
  • Reading a listing back returns exactly id, title, sku, price, created_at and reference_code.
  • internal_note is staff-only. It is not in the list, so it is neither readable nor settable: an internal_note in the body does not reach validated_data.

3. The values the server owns

  • id, created_at and reference_code are read-only.
  • Each one appears in the output, so a reader sees the id, the creation time and a reference_code of MKT-OAKTBL-001 for the sku OAKTBL-001.
  • 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 saved row carries the server's value.

4. The cost nobody reads back

  • cost_price is write-only: a client sends it, it is accepted into validated_data as a Decimal, and it never appears in the output of a read.
  • price stays readable, since that is the money a buyer may see.

5. The sku somebody already has

  • A payload whose sku is already stored fails is_valid() with an error under the sku key, and a free sku still validates.
  • It must never reach the database, because by then the only answer left is an IntegrityError out of save() - a 500 where a 400 with a readable message belonged.

Notes

  • ModelSerializer builds its fields by inspecting the model, so a column's type, length, precision, blank-ness 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; a field already read-only by nature, such as the primary key or an auto_now_add column, is treated that way whether or not it is listed.
  • extra_kwargs passes keyword arguments to a field ModelSerializer generated, which is how a field becomes write_only without being retyped by hand.
  • 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 or a permission class: a serializer is the whole answer.

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