版本:1.1.0b2 |发布日期:2016年7月1日

SQLAlchemy 1.1文档

基本使用

SQLAlchemy对象关系配置涉及Tablemapper()和类对象的组合以定义映射类。declarative allows all three to be expressed at once within the class declaration. 尽可能使用常规SQLAlchemy模式和ORM结构,因此“古典”ORM使用和声明性之间的配置保持高度相似。

举一个简单的例子:

from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class SomeClass(Base):
    __tablename__ = 'some_table'
    id = Column(Integer, primary_key=True)
    name =  Column(String(50))

在上面,declarative_base()可调用返回一个新的基类,所有映射类都应该继承它。当类定义完成时,将会生成一个新的Tablemapper()

生成的表和映射器可以通过SomeClass类中的__table____mapper__属性访问:

# access the mapped Table
SomeClass.__table__

# access the Mapper
SomeClass.__mapper__

定义属性

在前面的示例中,Column对象会自动使用它们所分配的属性的名称进行命名。

要使用与其映射属性不同的名称明确命名列,只需为该列命名即可。Below, column “some_table_id” is mapped to the “id” attribute of SomeClass, but in SQL will be represented as “some_table_id”:

class SomeClass(Base):
    __tablename__ = 'some_table'
    id = Column("some_table_id", Integer, primary_key=True)

属性可以在其构造后添加到类中,并将它们根据需要添加到基础Tablemapper()定义中:

SomeClass.data = Column('data', Unicode)
SomeClass.related = relationship(RelatedInfo)

使用声明式构造的类可以与使用mapper()显式映射的类自由交互。

尽管不是必需的,但建议所有表共享相同的底层MetaData对象,以便可以毫无问题地解决字符串配置的ForeignKey引用。

访问MetaData

declarative_base()基类包含一个MetaData对象,其中收集了新定义的Table对象。此对象旨在直接访问MetaData特定的操作。例如,为所有表发出CREATE语句:

engine = create_engine('sqlite://')
Base.metadata.create_all(engine)

declarative_base() can also receive a pre-existing MetaData object, which allows a declarative setup to be associated with an already existing traditional collection of Table objects:

mymetadata = MetaData()
Base = declarative_base(metadata=mymetadata)

类构造函数

作为一个方便的功能,declarative_base()在接受关键字参数的类上设置一个默认构造函数,并将它们分配给指定的属性:

e = Engineer(primary_language='python')

映射器配置

声明在内部创建映射到声明表时使用mapper()函数。mapper()的选项直接通过__mapper_args__类属性传递。与往常一样,引用局部映射列的参数可以直接从类声明中引用它们:

from datetime import datetime

class Widget(Base):
    __tablename__ = 'widgets'

    id = Column(Integer, primary_key=True)
    timestamp = Column(DateTime, nullable=False)

    __mapper_args__ = {
                    'version_id_col': timestamp,
                    'version_id_generator': lambda v:datetime.now()
                }

定义SQL表达式

有关将属性声明性映射到SQL表达式的示例,请参阅SQL Expressions as Mapped Attributes