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
SynchronousOnlyOperationexception being raised by Django
This can be mitigated by:
- Setting
includeorexcluderules to only include necessary fields (docs) - Configuring nested relationships with an appropriate
max_nexted_depth(docs) - Using
select_relatedandprefetch_relatedto 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.
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
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file litestar_django-0.1.1.tar.gz.
File metadata
- Download URL: litestar_django-0.1.1.tar.gz
- Upload date:
- Size: 10.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
c37baaf743a508285e7def55d9a5548ef251e031f6625d2a98cf67fc770acc37
|
|
| MD5 |
c7558f2681d8b0682efc77758981be87
|
|
| BLAKE2b-256 |
84b55307d90c9f6185f62a22e4f6d106bcb3004cbf9ef1c7f14bb3ffb76553ab
|
Provenance
The following attestation bundles were made for litestar_django-0.1.1.tar.gz:
Publisher:
publish.yaml on litestar-org/litestar-django
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
litestar_django-0.1.1.tar.gz -
Subject digest:
c37baaf743a508285e7def55d9a5548ef251e031f6625d2a98cf67fc770acc37 - Sigstore transparency entry: 207254963
- Sigstore integration time:
-
Permalink:
litestar-org/litestar-django@f84e9b4ee4da566c1f4bc381daa0755c1284f8ee -
Branch / Tag:
refs/tags/v0.1.1 - Owner: https://github.com/litestar-org
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yaml@f84e9b4ee4da566c1f4bc381daa0755c1284f8ee -
Trigger Event:
release
-
Statement type:
File details
Details for the file litestar_django-0.1.1-py3-none-any.whl.
File metadata
- Download URL: litestar_django-0.1.1-py3-none-any.whl
- Upload date:
- Size: 8.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
fda5fdd134dfe90d3da97057561a782ad6850113bbdb974a037e3267040ca771
|
|
| MD5 |
3e57698fb86a6f255613029aef1d1ac8
|
|
| BLAKE2b-256 |
3ab6d5cebd7d6917b3b034ab4e959ce0b5e70c93417b3a3d24febaeecc84e756
|
Provenance
The following attestation bundles were made for litestar_django-0.1.1-py3-none-any.whl:
Publisher:
publish.yaml on litestar-org/litestar-django
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
litestar_django-0.1.1-py3-none-any.whl -
Subject digest:
fda5fdd134dfe90d3da97057561a782ad6850113bbdb974a037e3267040ca771 - Sigstore transparency entry: 207254968
- Sigstore integration time:
-
Permalink:
litestar-org/litestar-django@f84e9b4ee4da566c1f4bc381daa0755c1284f8ee -
Branch / Tag:
refs/tags/v0.1.1 - Owner: https://github.com/litestar-org
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yaml@f84e9b4ee4da566c1f4bc381daa0755c1284f8ee -
Trigger Event:
release
-
Statement type: