django-pydantic-models
A lightweight utility that converts Django models into fully-typed Pydantic models, supporting automatic field mapping, validation constraints, and nested model generation for related fields (ForeignKey, OneToOneField, ManyToManyField).
✨ Features
- 🔁 Automatic mapping from Django fields to Pydantic types
- 🧠 Smart support for Django field constraints:
max_length,choices,default,help_text,verbose_name
- 📦 Supports nested models for
ForeignKey,OneToOneField,ManyToManyField - ⚙️ Extensible with Pydantic validators and configuration
- 🛠️ Add or exclude fields selectively using
__fields__or__exclude__ - 🚀 Ideal for FastAPI, data validation, or serialization needs
📦 Installation
pip install django-pydantic-models
🛠 Usage
from django.db import models
from django_pydantic_models import django_model_to_pydantic
class Author(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField()
class Book(models.Model):
title = models.CharField(max_length=200, help_text="Title of the book")
published = models.BooleanField(default=False)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
tags = models.ManyToManyField("Tag")
class Tag(models.Model):
name = models.CharField(max_length=50)
@django_model_to_pydantic(Book)
class BookOut:
__fields__ = "__all__" # or list specific fields like ('title', 'author')
class Config:
config = {"populate_by_name": True}
__validators__ = {
"title": lambda v: v.title() # Example Pydantic validator
}
🧩 Field Mapping
Django fields are automatically mapped to their closest Pydantic equivalents. Examples:
| Django Field | Pydantic Type |
|---|---|
CharField |
str |
EmailField |
EmailStr |
URLField |
HttpUrl |
IntegerField |
int |
DateTimeField |
datetime |
ForeignKey |
nested Pydantic model |
ManyToManyField |
List[nested model] |
choices= |
Literal[...] |
🔍 Customization
Selecting fields
class BookOut:
__fields__ = ('title', 'author') # Include only
# or use __exclude__ = ('published',)
Validators
class BookOut:
__validators__ = {
"title": lambda v: v.strip().title()
}
Pydantic Config
class BookOut:
class Config:
config = {
"populate_by_name": True,
"extra": "forbid"
}
🧪 Initialization
Models can be initialized from a Django instance:
book = Book.objects.select_related("author").prefetch_related("tags").first()
pydantic_book = BookOut(book)
print(pydantic_book.model_dump())
Or with kwargs:
pydantic_book = BookOut(title="New Book", author=AuthorOut(...))
📄 License
This project is licensed under the MIT License. See the LICENSE file for details.
🤝 Contributing
Pull requests, issues, and feature suggestions are welcome! Please open an issue or PR.
📌 Why This Exists
Django models are great for ORM use but don't offer native support for fully typed external interfaces (e.g., APIs). django-pydantic-models bridges this gap, letting you use Django models for database interactions and automatically generate Pydantic models for typed validation and data exchange.
Metadata
Release files for django-pydantic-models 0.0.2
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| django_pydantic_models-0.0.2.tar.gz | 6.8 kB | Without provenance | Details for django_pydantic_models-0.0.2.tar.gz |
Release files / django_pydantic_models-0.0.2.tar.gz
| Download URL | django_pydantic_models-0.0.2.tar.gz |
|---|---|
| Size | 6.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
8b67e52740f7b484421ee7b642444bfeac3d5aff417c6b294c02f2087fa154a5
|
|
BLAKE2b-256 checksum How to use checksums |
b0b5ac5867dafc0b89385c1c45946107d7bc9f7e63e2b995c17b903d567d64b2
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/5.0.0 CPython/3.12.0
|
Security for django-pydantic-models 0.0.2
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.
No provenance found
None of the files in this release were uploaded with provenance metadata.
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.