设置关系attr会将对象添加到集合关系的会话中。有办法阻止这个吗?

时间:2011-05-23 10:22:55

标签: sqlalchemy

使用sqlalchemy,如果一个对象具有orm relation属性,并且您创建了该对象的实例,并设置了关系属性,那么您的新对象将被添加到set关系的会话中。 e.g:

from sqlalchemy import create_engine, Column, Integer, String, ForeignKey
from sqlalchemy.orm import relationship, Session
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()
class User(Base):
    __tablename__ = 'users'

    user_id = Column(Integer, primary_key=True)
    name = Column(String)

class Address(Base):
    __tablename__ = 'addresses'

    address_id = Column(Integer, primary_key=True)
    user_id = Column(Integer, ForeignKey(User.user_id),)
    address = Column(String)

    user = relationship(User, backref='addresses')


engine = create_engine('sqlite:///:memory:')
Base.metadata.create_all(engine)
session = Session(bind=engine)

bob = User()
bob.name = 'Bob'
session.add(bob)
session.commit()

bobs_addr = Address()
bobs_addr.user = bob
bobs_addr.address = "23 Bob's st."

# bobs_addr not added to the session

engine.echo = True
session.commit()

运行上述输出:

2011-05-23 12:07:23,461 INFO sqlalchemy.engine.base.Engine.0x...9a10 BEGIN (implicit)
2011-05-23 12:07:23,463 INFO sqlalchemy.engine.base.Engine.0x...9a10 SELECT users.user_id AS users_user_id, users.name AS users_name 
FROM users 
WHERE users.user_id = ?
2011-05-23 12:07:23,463 INFO sqlalchemy.engine.base.Engine.0x...9a10 (1,)
2011-05-23 12:07:23,466 INFO sqlalchemy.engine.base.Engine.0x...9a10 INSERT INTO addresses (user_id, address) VALUES (?, ?)
2011-05-23 12:07:23,466 INFO sqlalchemy.engine.base.Engine.0x...9a10 (1, "23 Bob's st.")
2011-05-23 12:07:23,467 INFO sqlalchemy.engine.base.Engine.0x...9a10 COMMIT

bobs_addr没有被添加到会话中,所以我希望它不会被提交到数据库,但是设置bobs_addr.user = bob导致bobs_addr被添加到会话中。我该如何阻止这种情况发生?

我知道有一种解决方法,那就是设置bobs_addr.user_id = bob.user_id,但我更喜欢使用关系attr。

1 个答案:

答案 0 :(得分:0)

我认为这可以达到您想要的效果,但我始终认为默认cascade='save-update, merge'效果最佳。

user = relationship(User, backref=backref('addresses', cascade=''))