【发布时间】:2018-08-13 15:33:17
【问题描述】:
当我尝试删除由 'id' 标识的类别实例及其 category_image 和文件实例时,如下所示:
c = Category.query.get(id)
for ci in c.images:
db.session.delete(ci)
db.session.flush()
for ci in c.images:
db.session.delete(ci.file)
db.session.flush() # if i type here db.session.commit() all is fine
db.session.delete(c)
db.session.commit()
我收到一个 AssertionError:依赖规则试图清除实例“”上的主键列“category_image.id_category”。但是,当我用提交替换删除 category_image.files 之后的刷新时,它就可以工作了。在我将 CategoryImage 表更改为中介后,我注意到了这一点。在更改之前,它有自己的 pk 没有合并,并且一切正常。这是我当前的模型定义。
class File(db.Model):
__tablename__ = 'file'
id_file = Column(Integer, Sequence('seq_id_file'), primary_key=True, nullable=False)
name = Column(Text, nullable=False)
path = Column(Text, nullable=False, unique=True)
protected = Column(Boolean, nullable=False, default=False)
class Category(db.Model):
__tablename__ = 'category'
id_category = Column(Integer, Sequence('seq_id_category'), primary_key=True, nullable=False)
name = Column(UnicodeText, nullable=False, unique=True)
images = relationship('CategoryImage', backref='images')
class CategoryImage(db.Model):
__tablename__ = 'category_image'
__table_args__ = (
PrimaryKeyConstraint('id_category', 'id_file', name='seq_id_category_image'),
)
id_category = Column(Integer, ForeignKey(Category.id_category), nullable=False)
id_file = Column(Integer, ForeignKey(File.id_file), nullable=False)
id_size_type = Column(Integer, nullable=)
file = relationship(File)
现在我正试图弄清楚刚刚发生了什么。如果我用错了,请纠正我。
【问题讨论】:
-
你看过stackoverflow.com/questions/23699651/…和stackoverflow.com/questions/35040724/…吗?这是关系级联尝试在删除父级时使外键为空。尽管您在会话中删除了它们,但它们仍然存在(当您在两者之间提交时不是这样)。
标签: python sqlalchemy flask-sqlalchemy