Sqlalchemy updates another model before uninstalling

I am using sqlalchemy with postgresql. And I'm new to sqlalchemy.

I made a forien key for the User model called to_user_id for the Invitation model, and this key is not NULL.

When I try to delete an instance of the User model using

session.delete(user) 

And sqlalchemy automatically sets the to_user_id prompt to NULL before deletion, and postgresql raises the following error.

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

How to disable it?

Here is my model definition

 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', ) 
+4
source share
1 answer

You must pass cascade='delete' to to_user relationship() . See here .

The ondelete argument for ForeignKey affects the generation of DDL statements, not the behavior of ORMs.

+3
source

All Articles