Skip to main content

sqlmodel-serializers

DRF like SQLModel serializer which allows us to create valid response schemes and easily add dynamic fields in responses

Installation

pip install sqlmodel-serializers

Usage

from sqlmodel_serializers import SQLModelSerializer


from .models import Hero


class HeroUpdate(SQLModelSerializer):
    class Meta:
        model = Hero

        optional = '__all__'

        fields = ('name', 'secret_name', 'age')


class HeroRead(SQLModelSerializer):
    id: int
    full_name: str

    class Meta:
        model = Hero


class HeroCreate(SQLModelSerializer):
    class Meta:
        model = Hero

        fields = ('name', 'secret_name', 'age')

Now you can create your routes like this:

from typing import List

from sqlmodel import Session, select
from fastapi import FastAPI, HTTPException, status

from .models import engine, Hero, create_tables
from .serializers import HeroRead, HeroCreate, HeroUpdate


app = FastAPI()


@app.on_event("startup")
def on_startup():
    create_tables(engine)


@app.post("/heroes", response_model=HeroRead)
def create_hero(data: HeroCreate):
    hero = Hero(**data.dict())

    with Session(engine) as session:
        session.add(hero)

        session.commit()

        session.refresh(hero)

        return hero


@app.get("/heroes", response_model=List[HeroRead])
def read_heroes():
    with Session(engine) as session:
        heroes = session.exec(select(Hero)).all()
        return heroes


@app.get('/heroes/pk', response_model=HeroRead)
def retrieve_hero(pk: int):
    with Session(engine) as session:
        instance  = session.get(Hero, pk)

        if not instance:
            raise HTTPException(
                detail='Hero not found',
                status_code=status.HTTP_404_NOT_FOUND
            )

        return instance

@app.patch('/heroes/{pk}', response_model=HeroRead)
def update_hero(pk: int, data: HeroUpdate):
    with Session(engine) as session:
        instance  = session.get(Hero, pk)

        if not instance:
            raise HTTPException(
                detail='Hero not found',
                status_code=status.HTTP_404_NOT_FOUND
            )

        hero_data = data.dict(exclude_unset=True)

        for key, value in hero_data.items():
            setattr(instance, key, value)

        session.add(instance)

        session.commit()

        session.refresh(instance)

        return instance

This results in these schemes

Schemes

Metadata

Release files for sqlmodel-serializers 0.0.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 sqlmodel-serializers 0.0.2
File Size Uploaded
sqlmodel-serializers-0.0.2.tar.gz 4.8 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for sqlmodel-serializers 0.0.2
File Interpreter ABI Platform
sqlmodel_serializers-0.0.2-py3-none-any.whl Python 3 none any Details

Total release size: 10.5 kB

Release files / sqlmodel-serializers-0.0.2.tar.gz

Download URL sqlmodel-serializers-0.0.2.tar.gz
Size 4.8 kB
Tags Source
SHA-256 checksum
How to use checksums
699ed64d615e360ea3f42fd12aa5bc4dbd04bfd56c284d31cc1745a8dc6dad17
BLAKE2b-256 checksum
How to use checksums
06dd31ca4860aad855f35eac90e9f15e52f5d6a8e83f34cba9c24e05637bb97f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.2 CPython/3.11.1

Release files / sqlmodel_serializers-0.0.2-py3-none-any.whl

Download URL sqlmodel_serializers-0.0.2-py3-none-any.whl
Size 5.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
b941c4439c6765437b4673b3b63f5bbb2d3da8ffd71f715d7c9e3cd41c9ff7ac
BLAKE2b-256 checksum
How to use checksums
bac3036ae097acb3ba14bd539eb80e1dce8a50b6d7c8feb4c6c1891925d7a85b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.2 CPython/3.11.1

Release history Release notifications | RSS feed

This release

0.0.2 This release

2 release files

0.0.1

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