Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy.declarative and deferred column loading

is it possible to specify some columns in the SQLAlchemy to be deferred-loading? I am using the sqlalchemy.ext.declarative module to define my mapping, example:

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

I want for example the column name be lazy loaded, how can I accomplish that?

Thank you Jan

like image 541
honzas Avatar asked Feb 18 '10 14:02

honzas


2 Answers

Just add deferred() around the column declaration:

class SomeClass(Base):
    __tablename__ = 'some_table'
    id = Column(Integer, primary_key=True)
    name =  deferred(Column(String(50)))
like image 122
Ants Aasma Avatar answered Oct 13 '22 11:10

Ants Aasma


Do not define the mapping for the columns which you want to load on demand. Then configure those as described in the Deferred Column Loading using mapper object. Modified code here:

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

Running this test code:

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

produces log extract:

... 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 = ?
like image 22
van Avatar answered Oct 13 '22 11:10

van