Skip to main content

pydantic-db aims to be a database framework agnostic modeling library. Providing functionality to convert database result object(s) into pydantic model(s). The aim is not to provide an ORM, but to target users who prefer raw sql interactions over obfuscated ORM object built queries layers.

For those who prefer libraries like pypika to build their queries, this library can still provide a nice layer between raw query results and database models.

So long as the database library you are using returns result objects that can be converted to a dictionary, pydantic-db will ineract cleanly with your results. See unittests for examples with asyncpg, mysql-connector-python, psycopg2 and sqlite3.

Usage

All examples assumes the existence of underlying tables and data, they are not intended to run as is.

from_result

To convert a single result object into a model, use Model.from_result.

import sqlite3

from pydantic_db import Model


class User(Model):
    id: int
    name: str


db = sqlite3.connect(":memory:")
db.row_factory = sqlite3.Row

stmt = "SELECT * FROM my_user LIMIT 1"
cursor.execute(stmt)
r = cursor.fetchone()

user = User.from_result(r)

from_results

To convert a list of result objects into models, use Model.from_results.

import sqlite3

from pydantic_db import Model


class User(Model):
    id: int
    name: str


db = sqlite3.connect(":memory:")
db.row_factory = sqlite3.Row

stmt = "SELECT * FROM my_user"
cursor.execute(stmt)
results = cursor.fetchall()

users = User.from_results(results)

Nested models

For more complicated queries returning a nested object, models can be nested. To parse them automatically prefix query fields with name__ format prefixes.

Say we have a Vehicle table with a reference to an owner (User).

import sqlite3

from pydantic_db import Model


class User(Model):
    id: int
    name: str


class Vehicle(Model):
    id: int
    name: str
    owner: User

db = sqlite3.connect(":memory:")
db.row_factory = sqlite3.Row

stmt = """
SELECT
    v.id,
    v.name,
    u.id AS owner__id,
    u.name AS owner__name
FROM my_vehicle v
JOIN my_user u ON v.owner_id = u.id
"""
cursor.execute(stmt)
results = cursor.fetchall()

vehicles = Vehicle.from_results(results)

Optional nested models

When a nested model is optional i.e. user: User | None the library will check if there is an id field by default, and if that field is empty (None), it will nullify that field.

If your nested model contains a differently named primary key or some other field that can be relied on to detect that a query has not successfully joined, and so the nested model should be None. Override the _skip_prefix_fields class var.

class User(Model):
    primary_key: int
    name: str


class Vehicle(Model):
    _skip_prefix_fields = {"owner": "primary_key"}

    id: int
    name: str
    owner: User | None

Metadata

Release files for pydantic-db 0.2.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 pydantic-db 0.2.1
File Size Uploaded Provenance Actions
pydantic_db-0.2.1.tar.gz 56.7 kB Without provenance Details for pydantic_db-0.2.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pydantic-db 0.2.1
File Interpreter ABI Platform Actions
pydantic_db-0.2.1-py3-none-any.whl Python 3 none any Details for pydantic_db-0.2.1-py3-none-any.whl

Total release size: 62.9 kB

Release files / pydantic_db-0.2.1.tar.gz

Download URL pydantic_db-0.2.1.tar.gz
Size 56.7 kB
Tags Source
SHA-256 checksum
How to use checksums
4e260f6057ce30083ab5d4ee1158445362b2d320a0f278f231d28b1f611fe466
BLAKE2b-256 checksum
How to use checksums
2de9591b5cfaf672e1716b0a0d2ae5d6adea06ae17bb67ebfda8259dc0bdba4a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.9.23

Release files / pydantic_db-0.2.1-py3-none-any.whl

Download URL pydantic_db-0.2.1-py3-none-any.whl
Size 6.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
787ea593dc50ba6289c6094d54e62507a3f49b47e1c756aef15a20005c8f1c05
BLAKE2b-256 checksum
How to use checksums
3b97ee761a8f1810c4aadef72808844813f37c7c01f02c985b25e9e37cd4eddb
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.9.23

Security for pydantic-db 0.2.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.

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.

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