Skip to content

Latest commit

 

History

History
47 lines (33 loc) · 940 Bytes

20220907132243.md

File metadata and controls

47 lines (33 loc) · 940 Bytes

sqlalchemy model from dataclass

I have mostly used the "Declarative Mapping way" of defining models in SQLAlchemy: https://docs.sqlalchemy.org/en/13/orm/mapping_styles.html

However if you want to define a model from say a dataclass, the "Classical Mapping" is a powerful alternative.

Example below and here: https://github.com/bbelderbos/sa-mapper-example

# schemas.py

from dataclasses import dataclass


@dataclass
class Car:
    model: str
    make: str
    year: int
    vin: str


# models.py

from sqlalchemy import (Column, Integer, MetaData,
                        String, Table)
from sqlalchemy.orm import mapper

from .schemas import Car

metadata = MetaData()

car = Table(
    'car',
    metadata,
    Column('id', Integer, primary_key=True),
    Column('model', String(50)),
    Column('make', String(20)),
    Column('year', Integer),
    Column('vin', String(50)),
)
mapper(Car, car)

#sqlalchemy #dataclasses