2010-02-18 92 views
5

是否可以指定SQLAlchemy中的某些列以延遲加載?我現在用的是sqlalchemy.ext.declarative模塊來定義我的映射,例如:SQLAlchemy.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)) 

我想例如列名偷懶裝,我怎麼能做到呢?

謝謝 月

+0

是什麼你可能想要的理由o推遲加載?您是否願意更改模型或數據庫模式以使其工作? – van 2010-02-18 16:25:21

回答

10

只需添加deferred()繞柱聲明:

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

+1:簡單而美麗 – van 2010-02-18 19:42:01

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 = ?