diff options
author | Mike Bayer <mike_mp@zzzcomputing.com> | 2012-01-28 17:41:10 -0500 |
---|---|---|
committer | Mike Bayer <mike_mp@zzzcomputing.com> | 2012-01-28 17:41:10 -0500 |
commit | 84cb539e5f1a0ed3626f8bc0cb42cf5493634786 (patch) | |
tree | 8c32f44ed71962c3ff06034a9b19a911cd291a8a /lib/sqlalchemy/ext/declarative.py | |
parent | 7e30b0ebd6d45e765415b9602f17594173690531 (diff) | |
download | sqlalchemy-84cb539e5f1a0ed3626f8bc0cb42cf5493634786.tar.gz |
declarative reflection example
Diffstat (limited to 'lib/sqlalchemy/ext/declarative.py')
-rwxr-xr-x | lib/sqlalchemy/ext/declarative.py | 35 |
1 files changed, 34 insertions, 1 deletions
diff --git a/lib/sqlalchemy/ext/declarative.py b/lib/sqlalchemy/ext/declarative.py index bd655a721..891130a48 100755 --- a/lib/sqlalchemy/ext/declarative.py +++ b/lib/sqlalchemy/ext/declarative.py @@ -264,7 +264,7 @@ to a table:: ``__table__`` provides a more focused point of control for establishing table metadata, while still getting most of the benefits of using declarative. An application that uses reflection might want to load table metadata elsewhere -and simply pass it to declarative classes:: +and pass it to declarative classes:: from sqlalchemy.ext.declarative import declarative_base @@ -313,6 +313,39 @@ a synonym for ``name``:: def name(self): return "Name: %s" % _name +Using Reflection with Declarative +================================= + +It's easy to set up a :class:`.Table` that uses ``autoload=True`` +in conjunction with a mapped class:: + + class MyClass(Base): + __table__ = Table('mytable', Base.metadata, + autoload=True, autoload_with=some_engine) + +However, one improvement that can be made here is to not +require the :class:`.Engine` to be available when classes are +being first declared. To achieve this, use the example +described at :ref:`examples_declarative_reflection` to build a +declarative base that sets up mappings only after a special +``prepare(engine)`` step is called:: + + Base = declarative_base(cls=DeclarativeReflectedBase) + + class Foo(Base): + __tablename__ = 'foo' + bars = relationship("Bar") + + class Bar(Base): + __tablename__ = 'bar' + + # illustrate overriding of "bar.foo_id" to have + # a foreign key constraint otherwise not + # reflected, such as when using MySQL + foo_id = Column(Integer, ForeignKey('foo.id')) + + Base.prepare(e) + Mapper Configuration ==================== |