Completely lazy loaded entity

25 views
Skip to first unread message

Andrey Popp

unread,
Feb 17, 2012, 5:37:50 PM2/17/12
to sqlal...@googlegroups.com
Hello,

is it possible to get completely lazy loaded entity? By completely lazy loaded
I mean no queries are done to database, so I have just instantiated object of
mapped class with only known attribute pk. If I access any other attribute
besides pk SQLAlchemy will load entire object state from database. Use case is
the following -- I have user's id encoded in cookie and want to have user
object attached to WSGI request, but if some of my views doesn't use it then it
shouldn't be queried from db.

Thanks!

Michael Bayer

unread,
Feb 17, 2012, 9:31:08 PM2/17/12
to sqlal...@googlegroups.com

it's not a built in use case, but to avoid any SQL whatsoever you'd need to make the object "persistent" in a fake way. Then you can get it in via merge():

from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.orm.util import identity_key
from sqlalchemy.orm.attributes import instance_state
from sqlalchemy.ext.declarative import declarative_base

Base= declarative_base()

class X(Base):
__tablename__ = "x"
id = Column(Integer, primary_key=True)
data = Column(String)

e = create_engine("sqlite://", echo=True)
Base.metadata.create_all(e)
s = Session(e)

s.add_all([
X(data='x1'), X(data='x2'), X(data='x3')
])
s.commit()
s.close()

def make_a_fake_detached_x(id):
# x with clean dict
x = X()
# give it a key
instance_state(x).key = identity_key(X, (id,))
return x

# use merge() with load=False so no SQL is emitted
x2 = s.merge(make_a_fake_detached_x(2), load=False)
assert 'data' not in x2.__dict__
assert x2.data == 'x2'


>
> Thanks!
>
> --
> You received this message because you are subscribed to the Google Groups "sqlalchemy" group.
> To post to this group, send email to sqlal...@googlegroups.com.
> To unsubscribe from this group, send email to sqlalchemy+...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/sqlalchemy?hl=en.
>

Andrey Popp

unread,
Feb 18, 2012, 4:42:39 PM2/18/12
to sqlal...@googlegroups.com
Thank you very much, I've implemented lazy_get method on my custom Query class and it works well, I've also made pk's attributes accessible w/o hitting the database — https://gist.github.com/77eb31670a1842f301c2
Reply all
Reply to author
Forward
0 new messages