尽管修改了对象,session.dirty仍为空

时间:2016-01-26 02:29:15

标签: python-3.x sqlalchemy

我正在关注官方教程并遇到了一个问题:即使我更改了一个对象,session.dirty调用也会给我一个空列表。我不确定是什么导致了它。在某些情况下,session.dirty的行为是否未定义?

以下是代码:

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import sessionmaker

engine = create_engine('sqlite:///:memory:', echo=True)
Base = declarative_base()

Session = sessionmaker(bind=engine)
session = Session()

class User(Base):
    __tablename__ = 'users'
    id       = Column(Integer, primary_key=True)
    name     = Column(String)
    fullname = Column(String)
    password = Column(String)

    def __repr__(self):
        return "User<name={}, fullname={}, password={}>".format(self.name, self.fullname, self.password)

# Create all tables
Base.metadata.create_all(engine)

ed_user = User(name='ed', fullname='Ed Jones', password='edspassword')
session.add(ed_user)
session.add_all([
    User(name='wendy', fullname='Wendy Williams', password='foobar'),
    User(name='mary', fullname='Mary Contrary', password='xxg527'),
    User(name='fred', fullname='Fred Flinstone', password='blah')
])
ed_user.password = 'f8s7ccs'
print(session.dirty) # Note: session.dirty without print does nothing

输出:

2016-01-26 07:57:43,149 INFO sqlalchemy.engine.base.Engine SELECT CAST('test plain returns' AS VARCHAR(60)) AS anon_1
2016-01-26 07:57:43,149 INFO sqlalchemy.engine.base.Engine ()
2016-01-26 07:57:43,150 INFO sqlalchemy.engine.base.Engine SELECT CAST('test unicode returns' AS VARCHAR(60)) AS anon_1
2016-01-26 07:57:43,150 INFO sqlalchemy.engine.base.Engine ()
2016-01-26 07:57:43,151 INFO sqlalchemy.engine.base.Engine PRAGMA table_info("users")
2016-01-26 07:57:43,151 INFO sqlalchemy.engine.base.Engine ()
2016-01-26 07:57:43,152 INFO sqlalchemy.engine.base.Engine 
CREATE TABLE users (
    id INTEGER NOT NULL, 
    name VARCHAR, 
    fullname VARCHAR, 
    password VARCHAR, 
    PRIMARY KEY (id)
)


2016-01-26 07:57:43,152 INFO sqlalchemy.engine.base.Engine ()
2016-01-26 07:57:43,152 INFO sqlalchemy.engine.base.Engine COMMIT
IdentitySet([])

1 个答案:

答案 0 :(得分:0)

好的,所以我自己弄清楚了。我在session.dirty中得不到任何东西,因为没有提交尚未进行比较。事实上,Ed的对象在session.new中可见。因此,当我执行session.commit()然后更改了Ed时,该对象在session.dirty中可用。