Last active
March 26, 2019 16:10
-
-
Save nicoddemus/c65c27ad60bc28376bc27ccec165c4c0 to your computer and use it in GitHub Desktop.
Quick example of using class-decorators to declare compound columns
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from sqlalchemy import create_engine | |
from sqlalchemy import Column, Float, Integer, String | |
from sqlalchemy.ext.declarative import declarative_base | |
engine = create_engine('sqlite:///:memory:', echo=True) | |
Base = declarative_base() | |
class ScalarField: | |
pass | |
def make_scalars(class_): | |
for attr_name in dir(class_): | |
attr_value = getattr(class_, attr_name) | |
if isinstance(attr_value, ScalarField): | |
setattr(class_, f'{attr_name}_unit', Column(String)) | |
setattr(class_, f'{attr_name}_value', Column(Float)) | |
return class_ | |
@make_scalars | |
class Fluid(Base): | |
__tablename__ = 'fluid' | |
id = Column(Integer, primary_key=True) | |
density = ScalarField() | |
def __repr__(self): | |
return f"<Fluid(density_value={self.density_value}, density_unit='{self.density_unit}')>" | |
Base.metadata.create_all(engine) | |
f = Fluid(density_value=1000.0, density_unit='kg/m3') | |
from sqlalchemy.orm import sessionmaker | |
Session = sessionmaker(bind=engine) | |
session = Session() | |
session.add(f) | |
print(session.query(Fluid).first()) |
igortg
commented
Mar 26, 2019
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment