views:

38

answers:

1

While using SQLAlchemy, i add a object to a session using session.add(objname), then either explicitly flush it using session.flush or enable autoflush=True while creating the engine itself.

Now in the session, if want to return that object via session.query(classname).all(), i cannot retrieve it.

Why is that so? or is there a way in which query() can also retrieve flushed objects.

+2  A: 

I can't reproduce your issue. Please provide sample code that I can run to reproduce it.

Here's code that does what you describe, but behaves as one would expect:

from sqlalchemy import Column, Integer, Unicode, create_engine
from sqlalchemy.orm import create_session
from sqlalchemy.ext.declarative import declarative_base

engine = create_engine('sqlite://')
Base = declarative_base(bind=engine)

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(Unicode(60))

Base.metadata.create_all()   

After that setup, Add a new user:

s = create_session(autocommit=False, autoflush=False)
u = User()
u.name = u'Cheezo'
s.add(u)
s.flush()

Then query it back:

>>> u2 = s.query(User).first()
>>> print u2.name
Cheezo
>>> u2 is u
True
nosklo
Thanks.This seems to work fine for me as well. But the problem i face when pass the session across multiple levels of functions. so if A() passes the session to B(), i can access the uncommitted object. But if A()->B()->C() (while passing the session all along) and i try to access this object in C. It complaints that the object does not exist.What could i be missing?
Cheezo
@Cheezo: I don't know. It should work. Perhaps you should provide a small, working script, that reproduces the issue -- Or maybe just modify my script in a way that reproduces your issue. I've tried adding many levels of functions and everything works fine.So, as I said in the first sentence of my answer **Please provide sample code that I can run to reproduce it**.
nosklo
I was able to solve the problem. The problem arised due to fact that i was infact using different session objects. I adding the object to one session but trying to retrieve in another session, which was causing the problem.Thanks for you help nosklo !
Cheezo