gpt4 book ai didi

python - SQLAlchemy - 在另一个实例 __init__ 中创建一个实例

转载 作者:行者123 更新时间:2023-12-01 06:05:18 24 4
gpt4 key购买 nike

对 SQLAlchemy 来说还是个新手(所以我的术语可能有点偏差)。我想在另一个数据库对象的构造函数中创建一个数据库对象,但问题是我无法将所述对象添加到 session 中,因此出现错误。

我的架构看起来有点像下面这样:

class Tag(Base):
__tablename__ = 'tag'

id = Column(Integer, Sequence('tag_id_seq'), primary_key=True, nullable=False)
type = Column(String(1), nullable=False)
name = Column(String(255), unique=True, nullable=False)

def __init__(self, type, name):
self.type=type
self.name=name

def __repr__(self):
return "<Tag('%s')>" % (self.id)


class Venue:
__tablename__ = 'venue'

tag_id = Column(Integer)
tag_type = Column(String(1), nullable=False)
location = Column(String(255), nullable=False)

tag = ForeignKeyConstraint(
(tag_id, tag_type),
(Tag.id, Tag.type),
onupdate='RESTRICT',
ondelete='RESTRICT',
)

def __init__(self,name,location):
self.tag = Tag('V',name)
self.location = location

当我执行以下操作时:

session.add(Venue("Santa's Cafe","South Pole"))

我收到错误:

UnmappedInstanceError: Class '__builtin__.instance' is not mapped

我认为这是因为在 Venue 构造函数中创建的 Tag 对象未添加到 session 中。我的问题是我如何/何时执行此操作。 (如果可能的话,我真的更愿意在构造函数中创建该 Tag 对象)。我认为我可以使用scoped_session 来做到这一点,但这似乎是一个非常糟糕的解决方案。

谢谢

最佳答案

  1. 继承Venue来自Base 。否则Venue不会被映射。
  2. 移动ForeignKeyConstraint __table_args__ .
  3. 替换当前无意义的tag属性 relationshipTag 。默认值cascade参数relationship包含'save-update'将新引用的对象添加到与父级相同的 session 的规则。

来自documentation:

save-update - cascade the Session.add() operation. This cascade applies both to future and past calls to add(), meaning new items added to a collection or scalar relationship get placed into the same session as that of the parent, and also applies to items which have been removed from this relationship but are still part of unflushed history.

关于python - SQLAlchemy - 在另一个实例 __init__ 中创建一个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8283403/

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