# sqlmodel-serializers
DRF like SQLModel serializer which allows us to create valid response schemes and easily add dynamic fields in responses
# Installation
```bash
pip install sqlmodel-serializers
```
# Usage
```python
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:
```python
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](https://notabug.org/kapustlo/sqlmodel-serializers/raw/master/images/schemes.webp?raw=true "Schemes")
Raw data
{
"_id": null,
"home_page": "https://notabug.org/kapustlo/sqlmodel-serializers",
"name": "sqlmodel-serializers",
"maintainer": "",
"docs_url": null,
"requires_python": ">=3.9",
"maintainer_email": "",
"keywords": "python,sqlmodel,pydantic,sqlalchemy,orm,serializer",
"author": "Kapustlo",
"author_email": "",
"download_url": "https://files.pythonhosted.org/packages/06/dd/31ca4860aad855f35eac90e9f15e52f5d6a8e83f34cba9c24e05637bb97f/sqlmodel-serializers-0.0.2.tar.gz",
"platform": null,
"description": "\n# sqlmodel-serializers\n\nDRF like SQLModel serializer which allows us to create valid response schemes and easily add dynamic fields in responses\n\n\n# Installation\n\n```bash\npip install sqlmodel-serializers\n```\n\n\n# Usage\n\n\n```python\nfrom sqlmodel_serializers import SQLModelSerializer\n\n\nfrom .models import Hero\n\n\nclass HeroUpdate(SQLModelSerializer):\n class Meta:\n model = Hero\n\n optional = '__all__'\n\n fields = ('name', 'secret_name', 'age')\n\n\nclass HeroRead(SQLModelSerializer):\n id: int\n full_name: str\n\n class Meta:\n model = Hero\n\n\nclass HeroCreate(SQLModelSerializer):\n class Meta:\n model = Hero\n\n fields = ('name', 'secret_name', 'age')\n```\n\nNow you can create your routes like this:\n\n\n```python\nfrom typing import List\n\nfrom sqlmodel import Session, select\nfrom fastapi import FastAPI, HTTPException, status\n\nfrom .models import engine, Hero, create_tables\nfrom .serializers import HeroRead, HeroCreate, HeroUpdate\n\n\napp = FastAPI()\n\n\n@app.on_event(\"startup\")\ndef on_startup():\n create_tables(engine)\n\n\n@app.post(\"/heroes\", response_model=HeroRead)\ndef create_hero(data: HeroCreate):\n hero = Hero(**data.dict())\n\n with Session(engine) as session:\n session.add(hero)\n\n session.commit()\n\n session.refresh(hero)\n\n return hero\n\n\n@app.get(\"/heroes\", response_model=List[HeroRead])\ndef read_heroes():\n with Session(engine) as session:\n heroes = session.exec(select(Hero)).all()\n return heroes\n\n\n@app.get('/heroes/pk', response_model=HeroRead)\ndef retrieve_hero(pk: int):\n with Session(engine) as session:\n instance = session.get(Hero, pk)\n\n if not instance:\n raise HTTPException(\n detail='Hero not found',\n status_code=status.HTTP_404_NOT_FOUND\n )\n\n return instance\n\n@app.patch('/heroes/{pk}', response_model=HeroRead)\ndef update_hero(pk: int, data: HeroUpdate):\n with Session(engine) as session:\n instance = session.get(Hero, pk)\n\n if not instance:\n raise HTTPException(\n detail='Hero not found',\n status_code=status.HTTP_404_NOT_FOUND\n )\n\n hero_data = data.dict(exclude_unset=True)\n\n for key, value in hero_data.items():\n setattr(instance, key, value)\n\n session.add(instance)\n\n session.commit()\n\n session.refresh(instance)\n\n return instance\n\n```\n\nThis results in these schemes\n\n![Schemes](https://notabug.org/kapustlo/sqlmodel-serializers/raw/master/images/schemes.webp?raw=true \"Schemes\")\n",
"bugtrack_url": null,
"license": "",
"summary": "Model serializer for SQLModel",
"version": "0.0.2",
"split_keywords": [
"python",
"sqlmodel",
"pydantic",
"sqlalchemy",
"orm",
"serializer"
],
"urls": [
{
"comment_text": "",
"digests": {
"md5": "53d16dbc81590b3bea75a7c0791a6fad",
"sha256": "b941c4439c6765437b4673b3b63f5bbb2d3da8ffd71f715d7c9e3cd41c9ff7ac"
},
"downloads": -1,
"filename": "sqlmodel_serializers-0.0.2-py3-none-any.whl",
"has_sig": false,
"md5_digest": "53d16dbc81590b3bea75a7c0791a6fad",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.9",
"size": 5762,
"upload_time": "2022-12-12T15:46:31",
"upload_time_iso_8601": "2022-12-12T15:46:31.343948Z",
"url": "https://files.pythonhosted.org/packages/ba/c3/036ae097acb3ba14bd539eb80e1dce8a50b6d7c8feb4c6c1891925d7a85b/sqlmodel_serializers-0.0.2-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"md5": "aa0b38c193c37888ea96f61b2b30b233",
"sha256": "699ed64d615e360ea3f42fd12aa5bc4dbd04bfd56c284d31cc1745a8dc6dad17"
},
"downloads": -1,
"filename": "sqlmodel-serializers-0.0.2.tar.gz",
"has_sig": false,
"md5_digest": "aa0b38c193c37888ea96f61b2b30b233",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.9",
"size": 4750,
"upload_time": "2022-12-12T15:46:33",
"upload_time_iso_8601": "2022-12-12T15:46:33.333837Z",
"url": "https://files.pythonhosted.org/packages/06/dd/31ca4860aad855f35eac90e9f15e52f5d6a8e83f34cba9c24e05637bb97f/sqlmodel-serializers-0.0.2.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2022-12-12 15:46:33",
"github": false,
"gitlab": false,
"bitbucket": false,
"lcname": "sqlmodel-serializers"
}