Getting access to the internals of the sqlalchemy stack in turbogears can be difficult if you do not know where to look. The use of declarative_base() to create model classes further obfuscates the location of the table and metadata objects.
In order to create/drop a table using an SQLAlchemy object, you need access to the table object, the table metadata, and a database engine object. When extending DeclarativeBase, the table object is exposed by the __table__ attribute of every model class. For instance:
class Distro(DeclarativeBase):
__tablename__ = ‘distro’
id = Column(Integer, primary_key=True, unique=True)
label = Column(Unicode(35), nullable=False)
In [1]: from yourapp.model import *
In [2]: import transaction
In [3]: distro_obj = Distro()
In [4]: print distro_obj.__table__.__doc__
——> print(distro_obj.__table__.__doc__)
Represent a table in a database.
e.g.::
mytable = Table(“mytable”, metadata,
Column(‘mytable_id’, Integer, primary_key=True),
Column(‘value’, String(50))
)
As you can see, you may access the methods of Table() from the DeclarativeBase __table__ attribute. In order to use the model to create/drop the table it describes, you need to bind the table metadata to an instantiated SQLAlchemy engine object. Pylons, the framework which Turbogears 2+ is based, stores the engine (defined in the paster .ini configuration) in the config global configuration dictionary, specifically:
config['pylons.app_globals'].sa_engine
Going back to the model we created, we can create the table using the Table() method create.
distro_obj.__table__.create(config['pylons.app_globals'].sa_engine)
Now that the table is created you may use the session object to interact with the table.
In [5]: distro_obj.label = 'rhel5_minimal'
In [6]: DBSession.add(distro_obj)
In [7]: transaction.commit()
In [8]: distro_label = DBSession.query(Distro.label).filter(Distro.label=='rhel5_minimal').one()[0]
In [9]: print distro_label
-------> print(distro_label)
rhel5_minimal
For more information, take a look at the documentation for TG2.1 and SQLAlchemy declarative syntax.