Skip to main content

GraphQL-like sparse fieldsets and automatic query optimization for Django REST Framework

Project description

drf-partial-response-fields

CI PyPI version Python versions License: MIT

GraphQL-like sparse fieldsets for Django REST Framework — with automatic select_related / prefetch_related / only() query optimization, so requesting fewer fields also means fewer queries and less data transferred.

GET /api/articles/1/?fields=title,author(name,email),tags(label)
{
  "title": "Shipping Faster with Sparse Fieldsets",
  "author": { "name": "Ada Lovelace", "email": "ada@example.com" },
  "tags": [{ "label": "performance" }, { "label": "django" }]
}

Why

Fetching the full representation of a resource is wasteful when a client only needs a few fields — especially on mobile, in list views, or in BFF-style aggregation layers. Most "sparse fieldset" implementations for DRF only filter the serializer output and leave the ORM query untouched, so you save bytes on the wire but still pay for every join and every SerializerMethodField query. This package does both: it filters what gets serialized and rewrites the queryset so the database only does the work that's actually needed.

Features

  • Nested field selection: ?fields=title,author(name,email)
  • Deep nesting: any depth, e.g. author(company(name,address(city)))
  • Exclusion: ?fields=-internal_notes,-legacy_id
  • Aliasing: ?fields=publishedAt:created_at
  • Wildcards: ?fields=* (explicit "no restriction")
  • Works with: ModelSerializer, nested serializers, SerializerMethodField, pagination, ViewSet/GenericAPIView/APIView, the Browsable API, and OpenAPI schema generation (via drf-spectacular)
  • Automatic query optimization: select_related, prefetch_related (including recursively-optimized nested Prefetch querysets), and only() are derived from the requested fields — see docs/performance.md for measured query-count reductions.
  • Safe by default: unrequested SerializerMethodFields are never invoked, so expensive computed fields only cost what they cost when a client actually asks for them.
  • Fully typed, PEP 561 compatible, mypy --strict clean.

Installation

pip install drf-partial-response-fields

# with OpenAPI schema support
pip install drf-partial-response-fields[openapi]

Requires Python 3.10+, Django 4.2+, and Django REST Framework 3.14+.

Quick Start

# serializers.py
from rest_framework import serializers
from drf_partial_response_fields import PartialFieldsModelSerializer


class AuthorSerializer(PartialFieldsModelSerializer):
    class Meta:
        model = Author
        fields = ["id", "name", "email"]


class ArticleSerializer(PartialFieldsModelSerializer):
    author = AuthorSerializer()

    class Meta:
        model = Article
        fields = ["id", "title", "body", "author"]
# views.py
from rest_framework import viewsets
from drf_partial_response_fields import PartialResponseMixin


class ArticleViewSet(PartialResponseMixin, viewsets.ModelViewSet):
    queryset = Article.objects.all()
    serializer_class = ArticleSerializer

That's it — GET /articles/?fields=title,author(name) now returns only title and author.name, and the underlying queryset automatically gets select_related("author").only("id", "title", "author__id", "author__name").

See docs/quickstart.md and docs/advanced-usage.md for aliasing, exclusion, SerializerMethodField optimization hints, and plain-APIView integration.

Documentation

Full documentation is available at https://mahmoudgshake.github.io/MahmoudPackages/drf-partial-response-fields/, including:

Contributing

Contributions are welcome — see https://mahmoudgshake.github.io/MahmoudPackages/drf-partial-response-fields/contributing.

License

MIT — see LICENSE.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

drf_partial_response_fields-1.0.2.tar.gz (54.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

drf_partial_response_fields-1.0.2-py3-none-any.whl (27.4 kB view details)

Uploaded Python 3

File details

Details for the file drf_partial_response_fields-1.0.2.tar.gz.

File metadata

File hashes

Hashes for drf_partial_response_fields-1.0.2.tar.gz
Algorithm Hash digest
SHA256 23786430079b7762369584a60ee421b709f104f81d60da234dabd1bf493bcde8
MD5 0b1228e4e81775e15f5a6ce9ba178fa9
BLAKE2b-256 0772c1b3ebd15510e00a38203fa2126e40b7136477eb8ed7cfe79b9a980a7a22

See more details on using hashes here.

File details

Details for the file drf_partial_response_fields-1.0.2-py3-none-any.whl.

File metadata

File hashes

Hashes for drf_partial_response_fields-1.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 259b3c48eda3e8c411442db2ade3abfb368efed5f4e891d3dbde2adce039740c
MD5 5a9437d9484df148981552fd37b8c4e0
BLAKE2b-256 f310e909875c92806da22a3cd9e4bad157361faa0f1f6489fb40935020f30f02

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page