Skip to main content

drf-fast-output

Faster output serialization for Django REST Framework read endpoints, with the same output as stock DRF.

DRF's Serializer.to_representation does a lot of generic work for every field of every row: field.get_attribute() → fields.get_attribute() → getattr, a PKOnlyObject check, a method call to field.to_representation(), and for method sources (source="get_status_display") an inspect.signature() call per row. This package compiles each serializer into one generated Python function that does the same thing with that work inlined.

Serialization time only (benchmarks/bench.py, Python 3.15, Django 6.1), the same serializer as plain DRF classes vs fast:

case 1 row 5 rows 25 rows 2000 rows
ModelSerializer, fields='__all__' 0.91x 1.37x 2.61x 5.9x
Nested (FK, O2O, reverse FK, M2M, method fields) 0.91x 1.30x 2.45x 3.9x
fast_output() on a stock serializer 0.83x 1.07x 1.95x 5.5x

The small-row numbers include constructing the serializer. A single object is somewhat slower (up to ~17%), and everything from a handful of rows up gets faster. Compiled plans are shared by every serializer instance with the same field configuration, so each request only pays for binding its own field objects.

Usage

The options below all give the same result. Pick whichever fits your code.

1. Per serializer: mix it in before the DRF base class, or use the ready-made bases:

from drf_fast_output import FastOutputMixin, FastModelSerializer

class BookSerializer(FastOutputMixin, serializers.ModelSerializer):
    ...

class AuthorSerializer(FastModelSerializer):  # same thing
    ...

2. Per view, read requests only: leave your serializers untouched:

from drf_fast_output.views import FastOutputViewMixin

class BookViewSet(FastOutputViewMixin, viewsets.ModelViewSet):
    serializer_class = BookSerializer   # GET/HEAD/OPTIONS get the fast version

3. Wrap a class:

from drf_fast_output import fast_output

class BookList(generics.ListAPIView):
    serializer_class = fast_output(BookSerializer)  # cached subclass, same name/Meta

Nested serializers are compiled into the parent automatically, even plain DRF ones. Only output changes. Validation, is_valid() and save() are stock DRF.

Write endpoints

Fast serializers work on write endpoints. is_valid(), create(), update() and save() are untouched, and the response after save() goes through the fast path. The view mixin only switches serializers for reads by default. To include write responses, set fast_output_methods:

class BookViewSet(FastOutputViewMixin, viewsets.ModelViewSet):
    fast_output_methods = ("GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH")

A write response is usually a single object, so expect break-even rather than a speedup.

Renderers

The output is the same Python objects stock DRF produces, so any renderer gives the same bytes it would without this package. That includes DRF's JSONRenderer, drf-orjson-renderer, and XML or YAML renderers. The two speedups combine: on the nested benchmark above, JSONRenderer takes 7.2 ms to render what this package serializes in about 50 ms, and ORJSONRenderer takes 1.6 ms.

What gets inlined

Each readable field gets an access strategy and a conversion:

access used for
attr concrete model columns (o.title), FK pks (o.author_id)
fkobj forward FK/O2O to a nested serializer (o.author, missing → None)
prefetch to-many relations: reads Django's prefetch cache when populated
call model method sources such as get_FOO_display
method SerializerMethodField
get everything else: DRF's own field.get_attribute()

Conversions are inlined for CharField (and Email/Slug/URL/...), IntegerField, BigIntegerField, FloatField, BooleanField, ChoiceField, UUIDField, DateField, TimeField, DateTimeField (ISO-8601 output in UTC or with USE_TZ=False), JSONField, ReadOnlyField, PrimaryKeyRelatedField, many-pk fields, and nested serializers / many=True. Anything else, such as DecimalField, custom fields, or non-ISO formats, calls the field's own to_representation.

Correctness rules

  • A shortcut is only taken when the field class has not overridden the DRF method it replaces. A CharField subclass with its own to_representation still gets fast attribute access, but its conversion is its own.
  • Serializers that override to_representation are honoured. Nested ones are called as-is, and top-level ones still get the fast path when they call super().
  • Inline conversions are guarded by exact type checks (type(v) is str), and other values go to the field. For example, a TextChoices member or a SimpleLazyObject goes through the field's to_representation.
  • Instances that are not of Meta.model (dicts, other objects) take DRF's path for that row.
  • Relations that weren't prefetched, or were prefetched with to_attr, take DRF's path. The fast path never issues more queries than DRF.
  • Custom list_serializer_class is left alone. Its children are still fast.

When not to use it

The output is always correct, but there are cases where it doesn't help, or where its assumptions don't hold.

It won't be faster:

  • Single-object endpoints (detail views, write responses) are a little slower, at 0.83–0.91x of stock DRF in the benchmark. The gains need several rows, or nested lists inside the object (a detail view with 200 nested rows measured 1.5x). One edge case is a single object rendered through several small nested serializers. Each one is compiled for that request, and the setup can cost more than it saves. The worst case measured was about 6% slower. If an endpoint like that matters, give it a regular DRF serializer, or set Meta.fast_output = False on its serializer.
  • When serialization isn't the bottleneck. If the endpoint has N+1 queries or slow database calls, fix those first. This package doesn't change what gets queried.
  • When most fields fall back to DRF. Run explain(). Fields marked get or generic still go through DRF: DecimalField, DurationField, dotted sources (author.name), properties, reverse one-to-one, hyperlinked fields, custom fields, non-ISO date formats, and datetimes in a non-UTC timezone when USE_TZ=True. A serializer made mostly of these gains little.
  • Slow SerializerMethodFields. If a method does its own queries or heavy work, that cost is unchanged.

Avoid these patterns, or test them with VERIFY on:

  • Overriding all() on a related model's default manager. For prefetched relations the fast path reads Django's prefetch cache directly instead of calling .all(), so a custom all() is skipped. Relations that weren't prefetched still call it.
  • Changing a serializer after its first .data. A serializer compiles on first use and keeps the result. Swapping serializer.fields, field formats or choices, or a get_<name> method afterwards isn't picked up. Changes made in __init__ are fine.
  • Model subclasses that override serializable_value(). Only Meta.model itself is checked, not subclass instances.
  • Code that expects DRF's per-row lookups. A SerializerMethodField's method is looked up once per serializer instead of once per row. A model method used as a source (source="get_summary") is checked once up front instead of being re-inspected on every row.
  • Switching timezones while a list is being consumed. The active timezone is read once per many=True call, not per row. If the input is a generator that yields rows inside different timezone.override() blocks, all rows are rendered in the timezone that was active when serialization started. Stock DRF uses each row's. VERIFY catches this.

Other things to know:

  • VERIFY runs every serialization twice. Method fields run twice and queries can double, so use it in tests, not production.
  • Compiled code is cached per field configuration, up to 512 entries. Endpoints whose fields are chosen by the client (sparse fieldsets via ?fields=) can produce many configurations. Past the limit, the oldest entries are evicted and recompiled when they come back. That is always correct, but an endpoint that cycles through more than 512 combinations pays the compile cost again and again. The limit isn't configurable.
  • Errors raised inside the generated code have hard-to-read tracebacks. Frames show <drf_fast_output> without source lines. Set DRF_FAST_OUTPUT = {"ENABLED": False} to debug through stock DRF.
  • Mixin order matters. FastOutputMixin must come before the DRF base class. The wrong order raises a TypeError.
  • It generates Python code with exec. Only field names, prefetch keys and validated identifiers go into the generated source, but environments that forbid exec can't use it.
  • It depends on DRF and Django internals: _readable_fields, PKOnlyObject, choice_strings_to_values and _prefetched_objects_cache. Run your test suite with VERIFY on when you upgrade DRF or Django.

Settings

DRF_FAST_OUTPUT = {
    "ENABLED": True,   # master switch
    "VERIFY": False,   # compute stock DRF output too and raise on any difference
}

Turn on VERIFY in your test settings. Every fast serialization is then compared against stock DRF, checking types and key order as well, so 1 vs True or a reordered dict fails loudly. Lists are compared row by row as they are consumed, so generators behave as they do without VERIFY.

Both settings take effect on the next call, including on serializer instances that have already been used.

Opt a single serializer out with Meta.fast_output = False.

Debugging

>>> from drf_fast_output import explain
>>> print(explain(BookSerializer(qs, many=True)))
BookSerializer
    id: access=attr id conv=int
    title: access=attr title conv=str
    author: access=fkobj author conv=nested
        id: access=attr id conv=int
        name: access=attr name conv=str
    tags: access=prefetch tags conv=pklist
    status_display: access=call get_status_display conv=str
    price: access=attr price conv=generic

Fields with get or generic are the ones still going through DRF's machinery.

Development

uv sync
uv run pytest
uv run ruff check && uv run ruff format --check   # lint + formatting
uv run pyrefly check                              # type check
uv run python benchmarks/bench.py 2000   # large and small result sets

Every test in the suite renders through both paths and asserts identical output and no extra queries. It covers Python 3.10–3.15, Django 4.2–6.1 and DRF 3.15–3.18.

License

MIT. See LICENSE.

Metadata

Release files for drf-fast-output 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for drf-fast-output 0.1.0
File Size Uploaded Provenance Actions
drf_fast_output-0.1.0.tar.gz 21.7 kB With provenance Details for drf_fast_output-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for drf-fast-output 0.1.0
File Interpreter ABI Platform Actions
drf_fast_output-0.1.0-py3-none-any.whl Python 3 none any Details for drf_fast_output-0.1.0-py3-none-any.whl

Total release size: 44.8 kB

Release files / drf_fast_output-0.1.0.tar.gz

Download URL drf_fast_output-0.1.0.tar.gz
Size 21.7 kB
Tags Source
SHA-256 checksum
How to use checksums
4bf3b8dee37f04971f4606ca124401340fa3d08241317489f4d325fbcf7277bb
BLAKE2b-256 checksum
How to use checksums
12a18d54187810861de0871dec262e184be6245b80f544a8b300f27887b4211a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.

Transparency log

Release files / drf_fast_output-0.1.0-py3-none-any.whl

Download URL drf_fast_output-0.1.0-py3-none-any.whl
Size 23.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
052227fbaf580331ce3dcc5d9b49e2a181604f41659166d33469a19918e718d2
BLAKE2b-256 checksum
How to use checksums
c58ba98a3471c3104ba20791e40821ba56f905d98b043b77d33fd17c0774ec8f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.

Transparency log

Security for drf-fast-output 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for drf_fast_output-0.1.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page