DRF Serializers, ViewSets and Pagination

DRF Serializers, ViewSets and Pagination in Django: At a border, every parcel crossing in either direction passes a customs desk that works to one published…

The Analogy: A Customs Declaration and Inspection Hall

At a border, every parcel crossing in either direction passes a customs desk that works to one published schedule of what a declaration must contain. Inbound, an officer checks each parcel's declaration against that schedule -- required fields present, values in range, weights plausible -- and refuses anything malformed before it enters the country. Outbound, the same desk produces a clean official manifest from the country's own records, listing exactly the agreed fields in the agreed order. The schedule is the contract; both directions obey it, and nothing crosses that the schedule does not describe. A serializer is that schedule: one declaration of fields that validates what comes in and shapes what goes out.

Some entries on the manifest are stamped by the desk itself and cannot be dictated by the traveller -- the accession number, the date of entry, the officer's seal. A traveller who writes their own accession number is ignored, because the desk assigns it. Other entries run the opposite way: a declared valuation used to compute duty is recorded in the back-office ledger but never printed on the public manifest the traveller carries away. Read-only and write-only are exactly this: the desk decides which facts may flow inbound, which may flow outbound, and which stay sealed in the office.

The hall is laid out to a fixed floor plan so every traveller finds the same five windows -- inspect one parcel, list the day's parcels, register a new one, amend one, withdraw one -- and a single posted map wires that plan together. Because the hall cannot physically hold a whole day's traffic at the counter, travellers are called forward in fixed-size groups, each with a numbered ticket pointing at the next group. Nobody is ever handed the entire register at once. That standard floor plan is a ViewSet with its router, and the fixed-size groups with a next-ticket are pagination.

The failure is an officer who, to save time, stops working from the published schedule and photocopies the entire back-office ledger straight onto the public manifest. Now every parcel's manifest carries the internal risk flags, the informant notes, the duty-exemption codes -- facts that were never meant to leave the office. Worse, because the same shortcut runs inbound, a traveller can now write those internal fields on their own declaration and have them accepted as truth: someone stamps their own parcel "diplomatic, exempt" and walks it through. Copying every field in both directions turns a controlled contract into an open ledger, and the leak going out and the privilege escalation coming in are the same mistake seen from two sides.


Syntax or Core Structure

A DRF serializer is one class that declares the API's fields and, from that single declaration, both validates incoming JSON and renders outgoing JSON. A ModelSerializer reads the field list off the model; read_only_fields and write_only control direction. Here is the real class, then the round-trip reduced to a plain-Python pair you can run.

from rest_framework import serializers
from .models import Product


class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = ["id", "sku", "price", "cost"]
        read_only_fields = ["id"]
        extra_kwargs = {"cost": {"write_only": True}}

Each field carries two flags that decide its direction. A read_only field is rendered outbound but silently ignored on input; a write_only field is accepted on input but never rendered outbound. This spec and the two functions below encode exactly that rule.

FIELDS = [
    {"name": "id", "read_only": True, "write_only": False},
    {"name": "sku", "read_only": False, "write_only": False},
    {"name": "price", "read_only": False, "write_only": False},
    {"name": "cost", "read_only": False, "write_only": True},
]

def to_representation(obj):
    return {f["name"]: obj[f["name"]] for f in FIELDS if not f["write_only"]}

def to_internal(payload):
    return {f["name"]: payload[f["name"]] for f in FIELDS
            if not f["read_only"] and f["name"] in payload}

obj = {"id": 1, "sku": "PMP-1", "price": 1500, "cost": 900}
incoming = {"id": 999, "sku": "PMP-2", "price": 1800, "cost": 950}
rep = to_representation(obj)
intern = to_internal(incoming)
print("out: " + " ".join("%s=%s" % (k, rep[k]) for k in rep))
print("in: " + " ".join("%s=%s" % (k, intern[k]) for k in intern))

Output:

out: id=1 sku=PMP-1 price=1500
in: sku=PMP-2 price=1800 cost=950

Outbound, cost vanished because it is write-only. Inbound, the attacker's id=999 was dropped because id is read-only -- the desk assigns it, the client cannot. That single asymmetry is most of what keeps a DRF API honest: the client never dictates a server-owned field, and a secret never rides out on the response.


Technical Depth: Field Direction, Validation and Page Budgets

A field's options decide which way it flows

Every serializer field carries options that fix its direction and its rules. These five cover almost everything you reach for day to day, and misreading any one of them is how fields leak or silently vanish.

OptionDirectionEffect
read_onlyoutbound onlyrendered in responses, ignored on input
write_onlyinbound onlyaccepted on input, never rendered out
requiredinboundinput must supply it or validation fails
defaultinboundvalue used when the input omits the field
sourcebothmaps the field to a differently named model attribute

The pairing that trips people up is read_only versus required. A read-only field is never required on input because the client is not allowed to set it at all; marking a server-assigned field required is a contradiction that DRF will not enforce the way you expect.

Validation is field-level, then object-level

DRF validates each field on its own first, and only if every field passed does it run object-level validate() for cross-field rules. That ordering matters: a cross-field rule can assume the individual values are already well-formed. This stand-in runs field checks, and only when they all pass does it apply the object-level rule that a discount cannot exceed the price.

def validate(p):
    errors = []
    sku = p.get("sku", "").strip()
    if not sku:
        errors.append("sku: this field is required")
    price = p.get("price", 0)
    if price <= 0:
        errors.append("price: must be a positive integer")
    disc = p.get("discount", 0)
    if disc < 0:
        errors.append("discount: must be a non-negative integer")
    if not errors and disc > price:
        errors.append("discount: cannot exceed price")
    return errors

PAYLOADS = [
    {"sku": "PMP-1", "price": 1500, "discount": 100},
    {"sku": "", "price": 1500, "discount": 100},
    {"sku": "PMP-2", "price": 0, "discount": 0},
    {"sku": "PMP-3", "price": 500, "discount": 800},
]
for p in PAYLOADS:
    errs = validate(p)
    if errs:
        print("400 " + "; ".join(errs))
    else:
        print("201 created " + p["sku"])

Output:

201 created PMP-1
400 sku: this field is required
400 price: must be a positive integer
400 discount: cannot exceed price

The fourth payload is the interesting one: every field is individually valid, so the object-level rule runs and rejects it because the discount exceeds the price. Had price been zero as well, you would see the field error instead, because the object-level check never runs on already-broken input.

Pagination styles decide how a client walks a large result

DRF ships three pagination classes, and the choice is not cosmetic. Each trades ease of use against correctness under concurrent writes. Page-number pagination is the friendliest to read but the least stable; cursor pagination is the opposite.

Pagination classHow the client asksStable under inserts
PageNumberPaginationpage number, fixed page sizeno, rows shift between pages
LimitOffsetPaginationlimit plus offset into the setno, same offset drift
CursorPaginationopaque cursor on an ordered fieldyes, cursor pins a position

The instability of the first two is the same underlying problem: a page is defined by counting from the start, so an insert or delete near the front shifts every later row by one, and a client paging through can see a row twice or skip it entirely. Cursor pagination encodes an ordered field value instead of a count, so a new row does not renumber the ones already delivered.


Real World Example: A Paginated Product Catalogue Endpoint

A storefront exposes its active products through a read API. The endpoint hides internal fields such as cost, filters out inactive rows, and hands the client one fixed-size page at a time with a pointer to the next page. Here is the whole thing as a plain-Python stand-in: the product table is a list of tuples, public() is the outbound serializer, and list_page() is the paginated view.

PRODUCTS = [
    (1, "PMP-1", 1500, 900, True),
    (2, "HSE-1", 300, 120, True),
    (3, "CLP-1", 80, 30, False),
    (4, "VLV-1", 640, 400, True),
    (5, "GAU-1", 220, 100, True),
]
PAGE_SIZE = 2

def active():
    return [p for p in PRODUCTS if p[4]]

def public(p):
    return {"id": p[0], "sku": p[1], "price": p[2]}

def list_page(page):
    rows = active()
    total = len(rows)
    pages = (total + PAGE_SIZE - 1) // PAGE_SIZE
    start = (page - 1) * PAGE_SIZE
    chunk = rows[start:start + PAGE_SIZE]
    items = [public(p) for p in chunk]
    nxt = page + 1 if page < pages else None
    return items, pages, nxt

leaked = 0
for p in PRODUCTS:
    if "cost" in public(p):
        leaked = leaked + 1

print("count: " + str(len(active())))
items1, pages1, next1 = list_page(1)
print("page 1/" + str(pages1) + ": " + ",".join(i["sku"] + "(" + str(i["price"]) + ")" for i in items1))
print("next: " + (str(next1) if next1 else "none"))
items2, pages2, next2 = list_page(2)
print("page 2/" + str(pages2) + ": " + ",".join(i["sku"] + "(" + str(i["price"]) + ")" for i in items2))
print("next: " + (str(next2) if next2 else "none"))
print("leaked cost fields: " + str(leaked))

Output:

count: 4
page 1/2: PMP-1(1500),HSE-1(300)
next: 2
page 2/2: VLV-1(640),GAU-1(220)
next: none
leaked cost fields: 0

Trace the numbers by hand. Five products exist, but CLP-1 is inactive, so active() returns four rows and count is 4. With a page size of two, that is two pages. Page one serves PMP-1 and HSE-1 and reports next: 2; page two serves VLV-1 and GAU-1 and reports next: none because it is the last page. Every served row went through public(), which names exactly three keys, so cost never appears and leaked cost fields is zero.

The clean part is the outbound contract. Because public() lists its keys explicitly, a reviewer can see at a glance that cost cannot escape, and adding a new internal column to PRODUCTS will not silently start leaking it. That is exactly the discipline a hand-written serializer buys you over fields = "__all__", which would expose every column the moment someone adds one.

But the code has real flaws worth naming. First, active() materializes every matching row into a Python list on every request and then slices it, so a catalogue of a million products loads a million rows into memory to hand back two; a real view must push the filter and the slice down into the database as WHERE active LIMIT 2 OFFSET 0. Second, count walks the whole active set a second time, a separate full scan where the database could answer with a single COUNT(*). Third, public() is hand-maintained and drifts silently from the model: nothing forces it to stay in sync with the columns, so a renamed field breaks it only at runtime. Fourth, offset-style pagination is unstable under concurrent inserts, exactly the flaw the pagination table described, and a busy catalogue would be better served by cursor pagination keyed on the product id.


Common Mistakes

  1. Using fields = "__all__" on a ModelSerializer. It leaks every column outbound, including ones you add later, and it accepts every column inbound, which is a mass-assignment hole. List fields explicitly so the contract is visible and change-controlled.
  1. Confusing read_only with required. A read-only field is never required on input because the client cannot set it; marking a server-assigned field required=True is a contradiction DRF will not honour the way you expect. Server-set values belong in read_only_fields, not in a required list.
  1. Putting a secret in the serializer but forgetting write_only. A password or token field without write_only=True is echoed straight back in the response body. Accepting a value and returning it are separate permissions; a credential should flow in only.
  1. Doing cross-field validation in validate_<field>. Per-field validators only see their own value. A rule like "discount cannot exceed price" needs both fields, so it belongs in object-level validate(), which runs only after every field passed.
  1. Assuming validate() runs on partial updates. On a PATCH, fields the client omitted are absent from validated_data, so a cross-field rule that reads both may see only one. Guard object-level rules for the keys actually present.
  1. Returning querysets without pagination. A list endpoint with no pagination class serializes the entire table into one response; the first large table turns a single request into a timeout. Set a default pagination class project-wide.
  1. Paginating an unordered queryset. Page-number and offset pagination assume a stable order; without an explicit order_by, the database may return rows in a different order each call, so pages overlap or skip. Always order the queryset you paginate.
  1. Triggering N+1 queries inside the serializer. A nested field that reads a related object per row issues one query per item on the page. Use select_related and prefetch_related on the view's queryset so the related rows come back in one or two queries, not one per row.
  1. Validating in the view instead of the serializer. Scattering if checks across the view means each endpoint re-implements the same rules inconsistently. Validation belongs in the serializer, where it runs the same way for create and update and is testable in isolation.

Best Practices

  • List serializer fields explicitly. Name every field in Meta.fields rather than "__all__". Adding a column to the model should be a deliberate decision to expose it, not an automatic one.
  • Put server-controlled fields in read_only_fields. Ids, timestamps, and owner references are set by the server; declaring them read-only documents that intent and blocks a client from overriding them.
  • Mark credentials write_only. Anything the client sends but should never read back, such as a password, gets write_only=True so it is accepted on input and omitted from every response.
  • Keep cross-field rules in object-level validate(). Field validators enforce single-value rules; validate() enforces relationships between fields, and it runs only after the field-level checks pass, so it can trust the individual values.
  • Set a default pagination class. Configure DEFAULT_PAGINATION_CLASS and PAGE_SIZE in settings so every list endpoint is paginated by default and no view accidentally returns an unbounded result.
  • Order any queryset you paginate. Add an explicit order_by (often the primary key) so page boundaries are deterministic and clients never see a row twice or miss one.
  • Prefer cursor pagination for large, live tables. When rows are inserted frequently, cursor pagination pins a client's position to an ordered value instead of a count, avoiding the row-shifting that breaks page-number and offset styles.
  • Optimise the view's queryset, not the serializer. Attach select_related and prefetch_related on the view so related objects load in a bounded number of queries, keeping serialization from fanning out into an N+1 storm.

Practice Exercises

  1. Direction-aware serializer. Take the FIELDS list with read_only and write_only flags from the Syntax section and write both to_representation(obj) (skip write-only fields) and to_internal(payload) (skip read-only fields and fields absent from the payload). Feed it an object and an incoming payload where the client tries to set the read-only id, and confirm the id is ignored inbound while never being hidden outbound.
  1. Two-stage validator. Extend validate(p) to enforce a fourth rule: sku must be at most eight characters. Keep field-level checks (required sku, positive price, non-negative discount) running before the object-level "discount cannot exceed price" rule. Run it over a batch that triggers each error exactly once and verify the object-level rule never fires on a payload that already has a field error.
  1. Page walker. Using the PRODUCTS table and list_page(page), write a loop that starts at page 1 and follows next until it is none, collecting every served sku. Assert the collected list equals the active skus in order and that its length equals count, proving pagination neither drops nor repeats a row.
  1. Leak detector. Write a check that serializes every product with public() and asserts none of the returned dicts contains cost or active. Then deliberately switch public() to return the raw tuple's fields and watch the check fail, demonstrating why an explicit field list is safer than exposing the whole row.