gpt4 book ai didi

python - 如果在 SQLAlchemy 中将 "parent"对象分配给 "child",如何在 "relation"对象上设置属性?

转载 作者:行者123 更新时间:2023-12-04 10:27:46 24 4
gpt4 key购买 nike

当我有两个对象与 SQLAlchemy 中的“关系”相关联时,我意识到仅分配给该关系不足以将值传播到另一个对象。例如(见下文),如果我有一个“用户”表和一个“联系人”表(两者都是高度人为的,但很好地证明了问题),并且一个“用户”可以有多个“联系人”。在这种情况下,我将在用户和联系人之间使用外键。如果我同时创建 User 的实例和 Contact稍后将用户分配给联系人,我希望 FK 的属性会更新(即使没有数据库刷新),但事实并非如此。为什么?我如何告诉 SA 自动执行此操作?

这将是我期望的工作,但正如您在下面的完整示例中看到的那样,它没有:

user = User(name='a', lname='b')
contact(type='email', value='foo@bar.com')
contact.user = user
assert contact.username == 'a' # <-- Fails because the attribute is still `None`

完整的可运行示例:
"""
This code example shows two tables related to each other by a composite key,
using an SQLAlchemy "relation" to allow easy access to related items.

However, as the last few lines show, simply assigning an object A to the
relation of object B does not update the attributes of object B until at least
a "flush" is called.
"""
from sqlalchemy import Column, ForeignKeyConstraint, Unicode, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relation, sessionmaker

Base = declarative_base()

class User(Base):
__tablename__ = "user"

name = Column(Unicode, primary_key=True)
lname = Column(Unicode, primary_key=True)


class Contact(Base):
__tablename__ = "contact"
__table_args__ = (
ForeignKeyConstraint(
['username', 'userlname'],
['user.name', 'user.lname']
),
)

username = Column(Unicode, primary_key=True)
userlname = Column(Unicode, primary_key=True)
type = Column(Unicode)
value = Column(Unicode)

user = relation(User)


engine = create_engine('sqlite://')
Base.metadata.create_all(engine)

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

user = User(name="John", lname="Doe")
contact = Contact(type='email', value='john.doe@example.com')
contact.user = user # <-- How can I tell SA to set the FKs on *contact* here?
session.add(contact)

print('Before flush: contact.username user=%r' % contact.username)
session.flush()
print('After flush : contact.username user=%r' % contact.username)

最佳答案

根据这个答案 - https://stackoverflow.com/a/52911047/4981223这不可能:

The FK of the child object isn't updated until you issue a flush() either explicitly or through a commit(). I think the reason for this is that if the parent object of a relationship is also a new instance with an auto-increment PK, SQLAlchemy needs to get the PK from the database before it can update the FK on the child object (but I stand to be corrected!).

关于python - 如果在 SQLAlchemy 中将 "parent"对象分配给 "child",如何在 "relation"对象上设置属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60560238/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com