gpt4 book ai didi

python - Flask - SQLAlchemy 多对多原因 sqlalchemy.orm.exc.FlushError

转载 作者:行者123 更新时间:2023-12-01 01:59:52 26 4
gpt4 key购买 nike

class Show(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(200), unique=True, nullable=False)
studio = db.relationship("ShowStudio", backref="show", cascade="delete")

class Studio(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), unique=True, nullable=False)
show = db.relationship("ShowStudio", backref="studio", cascade="delete")

class ShowStudio(db.Model):
show_id = db.Column(db.Integer, db.ForeignKey(Show.id, ondelete="CASCADE"), primary_key=True)
studio_id = db.Column(db.Integer, db.ForeignKey(Studio.id, ondelete="CASCADE"), primary_key=True)

studio = Studio(name="asd")

db.session.add(studio)
s = Show(title="a", studio=[studio])
db.session.flush()

db.session.add(s)
db.session.commit()

当我运行它时,它抛出

sqlalchemy.orm.exc.FlushError: Attempting to flush an item of type as a member of collection "Studio.show". Expected an object of type or a polymorphic subclass of this type.

我遵循here的答案。我不明白是什么原因导致了错误。欢迎任何帮助。

最佳答案

many to many relationship 之间似乎有点混淆。并使用 association object pattern (这是多对多的变体)。鉴于您配置模型的方式 Show.studio 实际上是 one to many relationshipShowStudio 一起使用,因此它需要 ShowStudio 对象的集合,而不是 Studio:

studio = Studio(name="asd")    
db.session.add(studio)

showstudio = ShowStudio(studio=studio)
# You've disabled save-update cascade, so you have to
# add the association object to the session manually!
db.session.add(showstudio)

s = Show(title="a", studio=[showstudio])
db.session.add(s)

db.session.commit()

对于您最初的工作尝试,您需要使用 ShowStudio 底层表作为 ShowStudio 之间的多对多关系。 secondary :

class Show(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(200), unique=True, nullable=False)
studio = db.relationship("Studio", secondary="show_studio",
back_populates="show")

class Studio(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), unique=True, nullable=False)
show = db.relationship("Show", secondary="show_studio",
back_populates="studio")

class ShowStudio(db.Model):
show_id = db.Column(db.Integer, db.ForeignKey(Show.id, ondelete="CASCADE"),
primary_key=True)
studio_id = db.Column(db.Integer, db.ForeignKey(Studio.id, ondelete="CASCADE"),
primary_key=True)

由于 ShowStudio 中没有明确的 __tablename__ Flask-SQLAlchemy automatically sets it for youshow_studio

关于python - Flask - SQLAlchemy 多对多原因 sqlalchemy.orm.exc.FlushError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49811492/

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