如何在sqlalchemy中删除多对多关系中的行?

时间:2018-09-04 18:51:15

标签: python postgresql database-design orm sqlalchemy

当我尝试从task_details表中删除一行时,出现以下错误:

File "D:\My\venv\lib\site-packages\sqlalchemy\orm\relationships.py", line 1785, in _check_cascade_settings
% self)sqlalchemy.exc.ArgumentError: On User.tasks, delete-orphan cascade is not supported on a many-to-many or many-to-one relationship when single_parent is not set.   Set single_parent=True on the relationship().

我有一个user_details表和一个task_details表。这两者之间存在多对多的关系。有一个名为TaskMapping的关联表,该表具有user_id和task_id的映射。您可以在下面检查数据库设置:

TaskMapping = Table('TaskMapping', Base.metadata,
                   Column('user_id', Integer, ForeignKey('user_details.user_id')),
                   Column('task_id', Integer, ForeignKey('task_details.task_id', ondelete='CASCADE')))


class User(Base):
    __tablename__ = 'user_details'
    user_id = Column(Integer, Sequence('user_id_seq', start=1001, increment=1), primary_key=True)
    user_name = Column(String(250), nullable=False)
    email = Column(String(250), nullable=False)
    tasks = relationship('Tasks', backref='user_details', lazy = 'dynamic',
                         secondary=TaskMapping)


class Tasks(Base):
    __tablename__ = 'task_details'
    task_id = Column(Integer, Sequence('task_id_seq', start=1001, increment=1), primary_key=True)
    description = Column(String(250))
    hrs = Column(Float)
    percent_complete = Column(Float, default=0.0)
    users = relationship('User', backref='task_details', lazy = 'dynamic',cascade="all, delete-orphan",
                         single_parent=True, secondary=TaskMapping)

我愿意重新设计架构。

0 个答案:

没有答案