SQLAlchemy.declarative和延迟列加载

时间:2010-02-18 14:44:38

标签: python sqlalchemy

是否可以在SQLAlchemy中指定一些要延迟加载的列?我使用sqlalchemy.ext.declarative模块来定义我的映射,例如:

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))

我希望例如列名称是延迟加载的,我该如何实现呢?

谢谢 扬

2 个答案:

答案 0 :(得分:11)

只需在列声明周围添加deferred()

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

答案 1 :(得分:2)

不要为要按需加载的列定义映射。然后使用mapper对象按照Deferred Column Loading中的说明配置它们。这里修改了代码:

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))
    #big_name = Column(String(500))

SomeClass.__table__.append_column(Column('big_name', String(500)))
SomeClass.__mapper__.add_property('big_name', deferred(SomeClass.__table__.c.big_name))

运行此测试代码:

c = session.query(SomeClass).first()
# here SQL is loading all configured properties, but big_name
print "c: ", c
# only here another SQL request is made to load the property
print "big_name: ", c.big_name

生成日志提取:

... INFO sqlalchemy.engine.base.Engine.0x...77d0 SELECT some_table.id AS some_table_id, some_table.name AS some_table_name 
FROM some_table 
LIMIT 1 OFFSET 0

... INFO sqlalchemy.engine.base.Engine.0x...77d0 SELECT some_table.big_name AS some_table_big_name 
FROM some_table 
WHERE some_table.id = ?