Skip to content

Instantly share code, notes, and snippets.

@tlandschoff-scale
Created June 2, 2019 16:13
Show Gist options
  • Save tlandschoff-scale/83f6e1691d92236786a824cc79e359d1 to your computer and use it in GitHub Desktop.
Save tlandschoff-scale/83f6e1691d92236786a824cc79e359d1 to your computer and use it in GitHub Desktop.
Example showing how SQLAlchemy blends a property into a synonym
# encoding: utf-8
"""
Configuration of a `synonym` property via the mapper function actually
detects an existing property on the mapped class and blends this into
the propertyProxy it creates.
This is actually helpful but as of SQLAlchemy 1.3.4 this seems to be an
undocumented feature.
"""
from sqlalchemy import *
from sqlalchemy.orm import *
metadata = MetaData()
names_table = Table(
"names", metadata,
Column("id", Integer, primary_key=True),
Column("name", String),
)
class Name(object):
def __init__(self, name):
self.name = name
@property
def name(self):
return self._name
@name.setter
def name(self, name):
self._name = name[:1].upper() + name[1:]
mapper(Name, names_table, column_prefix="_", properties={
"name": synonym("_name"),
})
engine = create_engine("sqlite:///", echo=True)
metadata.create_all(engine)
session = sessionmaker(engine)()
t = Name("lowercased")
session.add(t)
session.commit()
print(session.query(Name.name).all())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment