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

Serialized Product Payload

mediumDjango REST FrameworkDRF Serializers—No data yet

Problem statement

In this Django project, declare the product wire format on the one serializer the endpoint now routes both directions through. app/views.py used to hand-build response dicts and reach into the raw body for whichever keys it hoped were there, so no two handlers agreed on what a product looks like and a price of cheap got as far as the database. Those dicts are gone, and ProductSerializer in app/serializers.py declares nothing: it renders an empty payload, accepts every body posted to it, and raises the moment anything asks it to save.

Requirements

Implement:

  • ProductSerializer, with its fields, create and update, in app/serializers.py

Only that file changes. app/models.py is read-only: Product holds name (CharField(max_length=50)), sku (CharField(max_length=12)), price (DecimalField(max_digits=8, decimal_places=2), validated at or above the minimum) and in_stock (BooleanField(default=True)), and the module exports MINIMUM_PRICE, whose value is 0.01. app/views.py and app/urls.py are given and complete: GET / answers with the running server's port, GET /api/products/ renders every product ordered by sku through the serializer with many=True, and POST /api/products/ builds the serializer with data=, answers 400 with serializer.errors when it does not validate and otherwise calls serializer.save() and answers 201 with serializer.data. The graded tests do not go through either view; they use the serializer directly.

1. The payload, declared field by field

  • ProductSerializer carries exactly these five keys in both directions, and many=True renders a list of them, one item per row, in the order the queryset handed them over.
KeyGoes out asComes in as
idthe row's integer idnever: read-only, and an id in the body is ignored rather than refused
namestringstring, at most 50 characters, required
skustringstring, at most 12 characters, required
pricestring carrying both decimal places, so 7.5 goes out as "7.50"number or numeric string, 8 digits and 2 decimal places, at least 0.01, required
in_stockbooleanboolean, required, with no default of its own
  • A DecimalField renders as a quoted string, and that is the default worth keeping: a decimal that travels as a JSON float loses cents.
  • in_stock has a default in the table but not in the payload, because a body that forgets to say whether a product is in stock is a body with a hole in it, not a body that means true.
  • No extra key on the way out, and no undeclared key accepted on the way in.

2. What a refused body reports

  • The bounds live on the declared fields, so each one is reported in errors under its own key and nothing else is: a missing field reports only itself, a mistyped value reports only its own field, a price under 0.01 reports only price, a 51-character name reports only name and a 13-character sku reports only sku.
  • An empty body therefore reports all four writable keys, and a body with several bad fields reports all of them at once while storing nothing.
  • A clean body leaves errors empty, and after is_valid() passes, validated_data holds the parsed values typed: price arrives as a Decimal and "true" as the boolean True.
  • id never appears in validated_data, even when the body carries one.

3. create(validated_data)

  • It stores a new product and returns it, built from validated_data and nothing else, so an id the body supplied does not become the row's id.
  • The returned object is the saved instance, because that return value is what save() hands back and what the serializer renders next.

4. update(instance, validated_data)

  • It writes the validated values onto the product it was given, saves it and returns it.
  • It touches that row only: an update adds no row, drops none, and leaves a product that was never part of the payload exactly as it was.

Notes

  • save() picks the method: no instance routes to create(validated_data), an instance routes to update(instance, validated_data). On a plain Serializer both are yours to write, and the base class raises NotImplementedError until they are.
  • ProductSerializer is a plain serializers.Serializer. A ModelSerializer, a Meta class or fields = "__all__" is not what this question asks for.
  • read_only=True marks a field that is rendered and never accepted, and a field with no required=False and no default is required.
  • Read validated_data in create and update, never initial_data: the body as posted holds unchecked values, strings where numbers belong, and keys no field declared.
  • Nothing re-sorts a many=True render for you; the order is the queryset's.
  • Do not add a view, a URL, a router, a generic view or a ViewSet, and do not reach for authentication or permissions: the serializer is the whole exercise.

More in DRF Serializers

See the module
Model 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 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.