Skip to main content

Litestar-Django

Django model support for Litestar, implemented via Litestar DTOs.

from litestar import get, Litestar
from litestar_django import DjangoModelPlugin
from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=100)


class Genre(models.Model):
    name = models.CharField(max_length=50)


class Book(models.Model):
    name = models.CharField()
    author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name="books")
    genres = models.ManyToManyField(Genre, related_name="books")


@get("/{author_id:int}")
async def handler(author_id: int) -> Author:
    return await Author.objects.prefetch_related("books").aget(id=author_id)


app = Litestar([handler], plugins=[DjangoModelPlugin()])

This minimal setup will provide serialization of Django objects returned from handlers, complete with OpenAPI schema generation.

Installation

pip install litestar-django

Usage

Directly constructing a DTO

from litestar import get
from litestar_django import DjangoModelDTO
from app.models import Author

@get("/{author_id:int}", dto=DjangoModelDTO[Author])
async def handler(author_id: int) -> Author:
    return await Author.objects.prefetch_related("books").aget(id=author_id)

Automatically creating DTOs via the plugin

from litestar import get
from litestar_django import DjangoModelPlugin
from app.models import Author

@get("/{author_id:int}")
async def handler(author_id: int) -> Author:
    return await Author.objects.prefetch_related("books").aget(id=author_id)

app = Litestar([handler], plugins=[DjangoModelPlugin()])

Creating a model instance from a DTO

from typing import Annotated
from litestar import post
from litestar.dto import DTOConfig
from litestar_django import DjangoModelDTO
from app.models import Author

@post(
    "/",
    sync_to_thread=True,
    dto=DjangoModelDTO[
       Annotated[
          Author,
          # exclude primary key and relationship fields
          DTOConfig(exclude={"id", "books"})
       ]
    ],
    return_dto=DjangoModelDTO[Author],
)
async def handler(data: Author) -> Author:
    await data.asave()
    return data

OpenAPI

Full OpenAPI schemas are generated from models based on their field types:

Type map

Field OpenAPI type OpenAPI format
models.JSONField {}
models.DecimalField number
models.DateTimeField string date-time
models.DateField string date
models.TimeField string duration
models.DurationField string duration
models.FileField string
models.FilePathField string
models.UUIDField string uuid
models.IntegerField integer
models.FloatField number
models.BooleanField boolean
models.CharField string
models.TextField string
models.BinaryField string byte

Additional properties

The following properties are extracted from fields, in addition to its type:

OpenAPI property From
title Field.verbose_name
description Field.help_text
enum Field.choices
exclusiveMinimum MinValueValidator
exclusiveMaximum MaxValueValidator
minLength MinLengthValidator
maxLength MaxLengthValidator

Relationships

Relationships will be represented as individual components, referenced in the schema.

Lazy loading

[!IMPORTANT] Since lazy-loading is not supported in an async context, you must ensure to always load everything consumed by the DTO. Not doing so will result in a SynchronousOnlyOperation exception being raised by Django

This can be mitigated by:

  1. Setting include or exclude rules to only include necessary fields (docs)
  2. Configuring nested relationships with an appropriate max_nexted_depth (docs)
  3. Using select_related and prefetch_related to ensure relationships are fully loaded

Foreign keys

When defining a ForeignKey field, Django will implicitly generate another field on the model with an _id suffix, to store the actual foreign key value. The DTO will include these implicit fields.

class Author(models.Model):
    name = models.CharField(max_length=100)

class Book(models.Model):
    name = models.CharField(max_length=100)
    author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name="books")

In this example, the DTO for Book includes the field definitions

  • id: int
  • name: str
  • author_id: int
  • author: Author

Serialization / validation of 3rd party field types

Additionally, the following 3rd party fields / types are supported if the DjangoModelPlugin is installed:

  • django-enumfields
  • django-enumfields2

Contributing

All Litestar Organization projects are open for contributions of any size and form.

If you have any questions, reach out to us on Discord or our org-wide GitHub discussions page.


Litestar Logo - Light
An official Litestar Organization Project

Release files for litestar-django 0.2.2

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

Source distribution (sdist)

Source distribution for litestar-django 0.2.2
File Size Uploaded
litestar_django-0.2.2.tar.gz 13.4 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for litestar-django 0.2.2
File Interpreter ABI Platform
litestar_django-0.2.2-py3-none-any.whl Python 3 none any Details

Total release size: 22.4 kB

Release files / litestar_django-0.2.2.tar.gz

Download URL litestar_django-0.2.2.tar.gz
Size 13.4 kB
Tags Source
SHA-256 checksum
How to use checksums
b4d32f6202c15dc917ccdb01bbf68474dcbb33de907da45c04d53502dc00800c
BLAKE2b-256 checksum
How to use checksums
b19870ad2bc2295fdec887a6fdf2e10cc518a9fca35e3849e79ed2f903bc89c7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.12.9

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 May 19, 2025.

Transparency log

Release files / litestar_django-0.2.2-py3-none-any.whl

Download URL litestar_django-0.2.2-py3-none-any.whl
Size 9.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
977d1c575ec3b8706bc004c9d1e393436c88a0a6680f3f27760c2f9ee587ec87
BLAKE2b-256 checksum
How to use checksums
ac11492e86dfe111ee769819185d75c55122e8753aa73b8b8f72cd94bec1b50e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.12.9

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 May 19, 2025.

Transparency log

Release history Release notifications | RSS feed

This release

0.2.2 This release

2 release files

0.2.1

2 release files

0.2.0

2 release files

0.1.1

2 release files

0.1.0

2 release files

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