我正在将 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 .
ForeignKey
的 ondelete
参数影响 DDL 语句的生成,而不是 ORM 的行为方式。
关于python - sqlalchemy 在删除之前更新另一个模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10990148/