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).al开发者_如何学JAVAl(), i cannot retrieve it.
Why is that so? or is there a way in which query() can also retrieve flushed objects.
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
精彩评论