Skip to main content

TurboDRF

PyPI Version Tests Coverage Python Django License

Dead simple Django REST Framework API generator with role-based permissions.

Turn your Django models into fully-featured REST APIs with a mixin and a method. Zero boilerplate.

Install

pip install turbodrf

# Optional: faster JSON rendering (7x faster than stdlib)
pip install turbodrf[fast]

Quick Start

1. Add to settings:

INSTALLED_APPS = [
    'rest_framework',
    'turbodrf',
]

2. Add the mixin to your model:

from django.db import models
from turbodrf.mixins import TurboDRFMixin

class Book(models.Model, TurboDRFMixin):
    title = models.CharField(max_length=200)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)
    price = models.DecimalField(max_digits=10, decimal_places=2)

    searchable_fields = ['title']

    @classmethod
    def turbodrf(cls):
        return {
            'fields': {
                'list': ['title', 'author__name', 'price'],
                'detail': ['title', 'author__name', 'author__email', 'price']
            }
        }

3. Add the router:

from turbodrf.router import TurboDRFRouter

router = TurboDRFRouter()

urlpatterns = [
    path('api/', include(router.urls)),
]

Done. You now have a full REST API with search, filtering, pagination, and field selection:

GET    /api/books/                          # List
GET    /api/books/1/                        # Detail
POST   /api/books/                          # Create
PUT    /api/books/1/                        # Update
DELETE /api/books/1/                        # Delete
GET    /api/books/?search=django            # Search
GET    /api/books/?price__lt=20             # Filter
GET    /api/books/?fields=title,price       # Select fields

Documentation

  • Configuration -- all turbodrf() options: field selection, nested & computed fields, custom endpoints (actions), read-only endpoints, method allow-lists, full_clean validation
  • Permissions -- role-based, field-level, and Django default permissions
  • Tenancy & row-level access -- predicates, multi-tenancy, FK injection defense
  • Performance -- compiled read path, fast JSON rendering, benchmarking
  • Filtering & Search -- filtering, search, ordering, OR queries
  • Integrations -- allauth, Keycloak, drf-api-tracking, Sentry (all experimental)
  • Security -- sensitive fields, secure defaults, error responses
  • Management Commands -- turbodrf_check, turbodrf_benchmark, turbodrf_explain
  • Settings Reference -- every TURBODRF_* setting in one place

Permissions and access control

TurboDRF answers four standard authorization questions, in three layers that all apply to every request (AND'd together):

Question Layer Mechanism
Can this user reach this endpoint? RBAC (Role-Based Access Control) Roles in TURBODRF_ROLES map to permissions. permissions.py checks <app>.<model>.<action> for the request method.
Which rows can this user see? Row-level access Predicates declared in turbodrf() config. Mandatory tenant boundary + discretionary within-tenant predicates (Owner, Members, Either, Custom).
Which fields can this user read or write? Field-level permissions Per-field rules <app>.<model>.<field>.read / .write in TURBODRF_ROLES. Hidden fields are stripped from responses, search, ordering, filters, and OPTIONS metadata.
Are FK targets the user provides actually theirs? Write validation On every create/update, FK and M2M values in the request body are validated against the related model's tenant boundary and predicate stack, on every model (shared ones included). Cross-tenant or invisible targets return 400.

Field rules bind anonymous callers too: public_access: True gives them model-level read, and a field that any role has a read rule for needs a grant from a guest role. See docs/permissions.md.

How it actually works (concrete walk-through)

A multi-tenant SaaS has two workspaces (ABC and XYZ) and three roles: member, manager, admin. A Project model is configured:

class Project(models.Model, TurboDRFMixin):
    workspace = models.ForeignKey(Workspace, on_delete=models.CASCADE)
    owner = models.ForeignKey(User, on_delete=models.CASCADE)

    @classmethod
    def turbodrf(cls):
        return {
            'tenant_field': 'workspace',                       # mandatory wall
            'owner_field': 'owner',             # within-tenant rule
            'bypass_owner_roles': ['manager', 'admin'],        # roles ignore owner check
            'fields': ['title', 'workspace', 'owner'],
        }

Plus two project-wide settings:

TURBODRF_TENANT_MODEL = 'accounts.Workspace'
TURBODRF_TENANT_USER_FIELD = 'workspace'   # request.user.workspace → tenant

Now a request GET /api/projects/ from Alice (member at ABC) goes through:

  1. Permission gate — Alice's role member has app.project.read. Pass.
  2. Tenant filter (mandatory, applied first, never bypassable):
    WHERE project.workspace_id = <Alice's workspace>
    
  3. Owner filter (Alice has no bypass role, so this layer applies):
    AND project.owner_id = <Alice's user id>
    
  4. Field stripping — Alice's role has read on title, workspace, owner but maybe not all configured fields. Hidden ones are removed from the response.

If Alice tries cross-tenant tricks:

  • GET /api/projects/<XYZ_project_id>/ → 404 (not 403, no existence leak)
  • PATCH /api/projects/<her_project_id>/ {"workspace": <XYZ>} → 400 (tenant reassignment rejected)
  • POST /api/comments/ {"document": <XYZ_bank_id>} → 400 (FK injection rejected)

If a manager (with bypass) at ABC asks for /api/projects/:

WHERE project.workspace_id = <ABC's workspace id>
-- no owner filter (manager bypassed it)

Manager sees all ABC projects, but still can't see XYZ — the tenant boundary is mandatory and applied separately from the predicate algebra (it's a setting, not a predicate). This rules out an entire class of compositional bugs where bypass roles could OR-compose their way past the tenant wall.

Performance

Tenant + owner predicates add ~0 measurable latency vs. the unscoped baseline (predicates compile to a single Q AND'd onto the queryset; the WHERE clause runs at the DB layer with index hits). FK injection check on writes adds ~one query per scoped FK / M2M field in the request body. Both are negligible for typical workloads. See docs/performance.md for benchmarking the compiled vs DRF read paths.

Quick recipes

# Multi-tenant SaaS — most common case
{'tenant_field': 'store', 'owner_field': 'customer', 'bypass_owner_roles': ['staff']}

# Personal data app (no TURBODRF_TENANT_MODEL; with one, owner_field alone fails the startup check)
{'owner_field': 'author', 'bypass_owner_roles': ['admin']}

# Reference data (currencies, country codes — not tenant-scoped)
{'tenancy': 'shared'}

# M2M membership (Slack channels, Linear projects)
{'tenant_field': 'workspace', 'visibility': [Members('participants')]}

# Power-form composition (when sugar doesn't fit)
{'tenant_field': 'workspace', 'visibility': [Either(Owner('owner'), Members('shared_with'))]}

See docs/tenancy.md for the full predicate vocabulary, hard-fail-at-startup behavior, and 404-vs-403 semantics.

License

MIT License. See LICENSE for details.

Metadata

Release files for turbodrf 0.6.1

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

Source distribution (sdist)

Source distribution for turbodrf 0.6.1
File Size Uploaded Provenance
turbodrf-0.6.1.tar.gz 412.5 kB With provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for turbodrf 0.6.1
File Interpreter ABI Platform
turbodrf-0.6.1-py3-none-any.whl Python 3 none any Details

Total release size: 549.4 kB

Release files / turbodrf-0.6.1.tar.gz

Download URL turbodrf-0.6.1.tar.gz
Size 412.5 kB
Tags Source
SHA-256 checksum
How to use checksums
e4682b3fbd82592cc74ca686bed5e3f8f689b94d60e643a7e2660c217d3b4cc3
BLAKE2b-256 checksum
How to use checksums
dac12cd59f3938643c73558a15ac90cd5bbd79d6c1229940b21cd978609318ca
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 Oct 22, 2026.

Transparency log

Release files / turbodrf-0.6.1-py3-none-any.whl

Download URL turbodrf-0.6.1-py3-none-any.whl
Size 137.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
82fcb635c6c7bbf540ffc431fbdc55a2895ad8863ae36306b973d4ee109e3811
BLAKE2b-256 checksum
How to use checksums
7e59bef9bfaabb3d1f88883f38076dff2e437182a3ae38e09819f0af8f50f01e
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 Oct 22, 2026.

Transparency log

Security for turbodrf 0.6.1

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

All 2 files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for turbodrf-0.6.1.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 Oct 22, 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.

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