这是设置:
class Photo(Model):
__tablename__ = "photo"
id = Column(Integer, primary_key=True, autoincrement=True)
filepath = Column(Text)
user_id = Column(Integer, ForeignKey("user.id", ondelete="CASCADE"))
user = db.relationship("User", foreign_keys=[user_id], back_populates="related_images", lazy=True)
class User(Model):
__tablename__ = "user"
id = Column(Integer, primary_key=True, autoincrement=True)
name = Column(Text)
related_images = db.relationship("Photo", foreign_keys=[Photo.user_id], back_populates="user", lazy=True, cascade="delete")
profile_image_id = Column(Integer, ForeignKey("photo.id", ondelete="CASCADE"))
profile_image = db.relationship("Photo", foreign_keys=[profile_image_id], lazy=True, post_update=True, cascade="delete")
我想删除用户的个人资料图片,所以我这样做:
user = get_user(user_id)
db.session.delete(user.profile_image)
db.session.commit()
这将成功从
Photo
表中删除该行,但是 user.profile_image_id
表上的 User
仍将保留旧照片 ID,在本例中为 id 1
。
如何删除用户的个人资料照片,以便将其从
User
表中删除(或不再引用)? ondelete
和 cascade='delete'
在这里似乎不起作用。
班级照片(模特): 表名 =“照片”
id = Column(Integer, primary_key=True, autoincrement=True)
filepath = Column(Text)
user_id = Column(Integer, ForeignKey("user.id", ondelete="CASCADE"))
user = db.relationship("User", foreign_keys=[user_id], back_populates="related_images", lazy='select')
类用户(型号): 表名 =“用户”
id = Column(Integer, primary_key=True, autoincrement=True)
name = Column(Text)
related_images = db.relationship("Photo", foreign_keys=[Photo.user_id], back_populates="user", lazy='select', cascade="all, delete-orphan")
profile_image_id = Column(Integer, ForeignKey("photo.id", ondelete="SET NULL"), nullable=True)
profile_image = db.relationship("Photo", foreign_keys=[profile_image_id], lazy='joined', post_update=True, cascade="all, delete-orphan")