python - sqlalchemy 在删除之前更新另一个模型

标签 python sqlalchemy

我正在将 sqlalchemy 与 postgresql 结合使用。我是 sqlalchemy 的新手。

我为名为“to_user_id”的模型“User”创建了一个 forien key 来模拟“Invitation”,这个键不可为空。

当我尝试使用

删除模型“用户”的实例时
session.delete(user)

并且 sqlalchemy 在删除之前自动将邀请的 to_user_id 设置为 NULL 并且 postgresql 引发以下错误。

IntegrityError: (IntegrityError) null value in column "to_user_id" violates not-null constraint

如何禁用它?

这是我的模型定义

class User(Base):
    '''
    User model
    '''
    __tablename__='User'
    id = Column(Integer,primary_key=True)

class Invitation(Base):
    '''
    Invitation model
    '''
    __tablename__ = 'Invitation'
    __table_args__ = (UniqueConstraint('appointment_id', 'to_user_id'),)
    id = Column(Integer, primary_key=True)

    appointment_id = Column(Integer,ForeignKey('Appointment.id',
        ondelete='CASCADE'), nullable=False)
    appointment = relationship('Appointment', backref=backref('invitations'),
    )

    from_user_id = Column(Integer,ForeignKey('User.id',
        ondelete='SET NULL'), nullable=True)
    from_user = relationship('User', backref=backref('sent_invitations'),
        primaryjoin='Invitation.from_user_id==User.id')

    to_user_id = Column(Integer,ForeignKey('User.id',
        ondelete='CASCADE'), nullable=False)
    to_user = relationship('User',backref=backref('received_invitations'),
        primaryjoin='Invitation.to_user_id==User.id',
    )

最佳答案

您应该将 cascade='delete' 传递给 to_user relationship()See the docs here .

ForeignKeyondelete 参数影响 DDL 语句的生成,而不是 ORM 的行为方式。

关于python - sqlalchemy 在删除之前更新另一个模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10990148/

相关文章:

python - 在以下Python脚本中需要帮助

python - 为什么 pandas Dataframe.to_csv 的输出与 Series.to_csv 不同?

python - mod_wsgi下的flask-sqlalchemy "no such table"

python - sqlalchemy "after_update"事件后级联更新

python - Snakemake选择了运行规则

Python模块搜索路径

python - 如何使用python从csv文件创建饼图

python - 如何更改抽奖的格式

python - 我可以让 SQLAlchemy 在不重复完整的原始查询的情况下进行子查询预加载吗?

python - 使用 alembic 获取表值并更新到另一个表。