Skip to main content

Django model support for Litestar

Project description

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

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

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

litestar_django-0.1.0.tar.gz (10.2 kB view details)

Uploaded Source

Built Distribution

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

litestar_django-0.1.0-py3-none-any.whl (8.0 kB view details)

Uploaded Python 3

File details

Details for the file litestar_django-0.1.0.tar.gz.

File metadata

  • Download URL: litestar_django-0.1.0.tar.gz
  • Upload date:
  • Size: 10.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for litestar_django-0.1.0.tar.gz
Algorithm Hash digest
SHA256 cd8ec86915f28d91ba51393b7a67dcf0fdcaa1fa1bab7dc2f29fb7f70f1e8a02
MD5 f123d5521254f543f50007c3b9b43263
BLAKE2b-256 9992b9020339861735c8e02116bd5ce488b4e61deccbfa4494c8cb1bb0fc92a7

See more details on using hashes here.

Provenance

The following attestation bundles were made for litestar_django-0.1.0.tar.gz:

Publisher: publish.yaml on litestar-org/litestar-django

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file litestar_django-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for litestar_django-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 c1ec362161a4b8c2ef3ad5c27b5eb6cc86a2b7ce4efb614366626f53c5b4ec1d
MD5 c98149352f506a8ce7d872173d9d956a
BLAKE2b-256 43662aab1d8226434b667c251f1fbc7c82652276f9d3501177de020bc40523b2

See more details on using hashes here.

Provenance

The following attestation bundles were made for litestar_django-0.1.0-py3-none-any.whl:

Publisher: publish.yaml on litestar-org/litestar-django

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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