SQLAlchemy 的声明式扩展在 0.5 中成为标准,提供了一个与 Django 或 Storm 非常相似的多合一接口。它还与使用 datamapper 样式配置的类/表无缝集成:
Base = declarative_base()
class Foo(Base):
__tablename__ = 'foos'
id = Column(Integer, primary_key=True)
class Thing(Base):
__tablename__ = 'things'
id = Column(Integer, primary_key=True)
name = Column(Unicode)
description = Column(Unicode)
foo_id = Column(Integer, ForeignKey('foos.id'))
foo = relation(Foo)
engine = create_engine('sqlite://')
Base.metadata.create_all(engine) # issues DDL to create tables
session = sessionmaker(bind=engine)()
foo = Foo()
session.add(foo)
thing = Thing(name='thing1', description='some thing')
thing.foo = foo # also adds Thing to session
session.commit()