在 SQLAlchemy 中删除时,一对多不会删除外键

问题描述 投票:0回答:1

这是设置:

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'
在这里似乎不起作用。

python python-3.x sqlalchemy flask-sqlalchemy
1个回答
0
投票

班级照片(模特): 表名 =“照片”

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")
© www.soinside.com 2019 - 2024. All rights reserved.