更新时间:2023-02-02 23:20:04
问题是sqlalchemy认为 Child
作为父对象,因为这是您定义关系的地方(当然,您在乎它是否称为孩子)。
The problem is that sqlalchemy considers Child
as the parent, because that is where you defined your relationship (it doesn't care that you called it "Child" of course).
如果而是在 Parent
类上定义关系,它将起作用:
If you define the relationship on the Parent
class instead, it will work:
children = relationship("Child", cascade="all,delete", backref="parent")
(请注意 Child
作为字符串:使用声明性样式时允许使用此字符串,这样您就可以引用尚未定义的类)
(note "Child"
as a string: this is allowed when using the declarative style, so that you are able to refer to a class that is not yet defined)
您可能还希望添加 delete-orphan
( delete
导致在删除父级时删除子级, delete-orphan
也会删除从父级删除的所有子级,即使未删除父级也是如此)
You might want to add delete-orphan
as well (delete
causes children to be deleted when the parent gets deleted, delete-orphan
also deletes any children that were "removed" from the parent, even if the parent is not deleted)
编辑:刚刚发现:如果您 rea lly 想要在 Child
类上定义关系,可以这样做,但是您必须在backref上定义级联 (通过显式创建backref),如下所示:
just found out: if you really want to define the relationship on the Child
class, you can do so, but you will have to define the cascade on the backref (by creating the backref explicitly), like this:
parent = relationship(Parent, backref=backref("children", cascade="all,delete"))
(暗指来自sqlalchemy.orm的导入backref
)
(implying from sqlalchemy.orm import backref
)