开发者

Setting a relation attr adds object to the session of the set relation. Is there a way to stop this?

With sqlalchemy, if one has an object with a orm relation attribute, and you create an instance of the object, and set the relation attribute, then your new object gets added to the session of the set relation. 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()

Output of running the above:

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.")
2开发者_JAVA百科011-05-23 12:07:23,467 INFO sqlalchemy.engine.base.Engine.0x...9a10 COMMIT

bobs_addr was not added to the session, so I would expect that it would not be committed to the db, however setting bobs_addr.user = bob caused bobs_addr to be added to the session. How do I stop this from happening?

There is a workaround that I am aware of, and that is to set bobs_addr.user_id = bob.user_id, but I would prefer to use the relation attr.


I think this can achieve what you want, but I have always found the default cascade='save-update, merge' to work best.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜