On Feb 17, 2012, at 5:37 PM, Andrey Popp wrote:
> 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.
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 [email protected].
> To unsubscribe from this group, send email to
> [email protected].
> For more options, visit this group at
> http://groups.google.com/group/sqlalchemy?hl=en.
>
--
You received this message because you are subscribed to the Google Groups
"sqlalchemy" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/sqlalchemy?hl=en.