如何从SQLAlchemy关系子表中删除所有行?

时间:2014-11-23 04:00:08

标签: python sqlalchemy

我当时认为这项任务相当简单,但我在谷歌搜索时没有运气。如果我有一个User表格,表格upload_list中有Videos个关系,那么如何清除upload_list表?

我用这种方式构建它:

class Users(base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    email = Column(String(100), unique=True)
    password = Column(String(255))
    fullname = Column(String(255))
    photo = Column(String(255))
    last_updated = Column(DateTime())

    upload_lists = relationship('UploadLists', cascade="all, delete, delete-orphan")


class UploadLists(base):
    __tablename__ = 'upload_lists'
    id = Column(Integer, primary_key=True)
    list_id = Column(String(255), unique=True)
    user_id = Column(Integer, ForeignKey('users.id'))
    user = relationship("Users")

    videos = relationship('Videos', cascade="all, delete, delete-orphan")


class Videos(base):
    __tablename__ = 'videos'
    id = Column(Integer, primary_key=True)
    video_id = Column(String(255), unique=True)
    title = Column(String(255))
    description = Column(String(255))
    upload_date = Column(DateTime)
    thumbnail_url = Column(Text())
    thumbnail_file = Column(Text())

1 个答案:

答案 0 :(得分:0)

是的,阅读this后,实际上解决方案非常明显。开始: s.query(models.UploadLists).filter(models.UploadLists.user_id == user.id).delete()

但是,上述模型似乎没有正确的级联删除配置。删除某些用户的UploadList仍然会将所有相关视频留在表Videos中。现在就开始研究,如果你知道答案,那么你在这里留下答案真是太棒了。如果这是一个正确答案,我会将其标记为已接受:)