Skip to content

Instantly share code, notes, and snippets.

@mikesname
Created February 20, 2012 21:11
Show Gist options
  • Save mikesname/1871448 to your computer and use it in GitHub Desktop.
Save mikesname/1871448 to your computer and use it in GitHub Desktop.
SQLAlchemy, dynamic table creation
def init_i18n_class(cls):
"""Create, via metadata reflection, an I18N class object
for i18n-enabled tables."""
tablename = cls.__tablename__ + "_i18n"
if Base.metadata.tables.get(tablename) is not None:
classname = cls.__name__ + "I18N"
i18nt = Table(tablename, Base.metadata,
Column("id", ForeignKey("%s.id" % cls.__tablename__), primary_key=True),
Column("culture", String(25), primary_key=True),
ForeignKeyConstraint(["id"], ["%s.id" % cls.__tablename__]),
autoload=True, extend_existing=True)
globals()[classname] =type(classname, (Base,), dict(__table__=i18nt))
setattr(cls, tablename, relationship(classname, cascade="all,delete-orphan",
primaryjoin="%s.id == %s.id" % (classname, cls.__name__)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment