我将 sqlalchemy 与 postgresql 一起使用。我是 sqlalchemy 的新手。
我为模型“用户”创建了名为“to_user_id”的 forien 键来建模“邀请”,并且该键不可为空。
当我尝试使用删除模型“用户”的实例时
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',
)