Skip to content

Instantly share code, notes, and snippets.

@estasney
Last active October 28, 2024 14:05
Show Gist options
  • Save estasney/81ea156262801140a12d99d0bbc3fa53 to your computer and use it in GitHub Desktop.
Save estasney/81ea156262801140a12d99d0bbc3fa53 to your computer and use it in GitHub Desktop.
Get ORM Attributes to Column Names
# This is useful for when an orm model has a property that references a column that has a different name
class Model():
__table_name__ = "sometable"
legacy_id = Column("id", Integer)
attrs = Model.__mapper__ # or inspect(Model)
{c.key: c.columns[0].key for c in attrs.column_attrs}
# {'legacy_id': 'id'}
# Additional utils
test_table = Table('test_table', i_meta,
Column('test_id', Integer, primary_key=True),
Column('dc_engagement_id', Integer, ForeignKey('dc_engagement_hdr.dc_engagement_id'), primary_key=True),
Column('engagement_name', String),
Column('some_value', String)
)
def get_primary_keys(orm_obj):
if not hasattr(orm_obj, 'primary_key'):
return list(inspect(orm_obj).primary_key)
return list(orm_obj.primary_key)
def get_table(orm_obj):
if isinstance(orm_obj, Table):
return orm_obj
elif isinstance(orm_obj, type) and hasattr(orm_obj, '__table__'):
return orm_obj.__table__
else:
raise ValueError(f"Invalid ORM object: {orm_obj}")
def get_relationships(orm_obj) -> set[ForeignKey]:
obj_table = get_table(orm_obj)
obj_meta = obj_table.metadata
ref_fk = set()
for table in obj_meta.tables.values():
if table != obj_table:
for constraint in table.constraints:
if isinstance(constraint, ForeignKeyConstraint):
for fk in constraint.elements:
if fk.references(obj_table):
ref_fk.add(fk)
return ref_fk
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment