Reputation: 595
I'm using sqlalchemy with postgresql. And I'm newbie of sqlalchemy.
I made forien key for model "User" called "to_user_id" to model "Invitation" and this key is not nullable.
When I try to delete instance of model "User" using
session.delete(user)
And sqlalchemy set invitation's to_user_id to NULL automatically before deletion and postgresql raise following error.
IntegrityError: (IntegrityError) null value in column "to_user_id" violates not-null constraint
How can I disable it?
Here's my model's 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',
)
Upvotes: 5
Views: 802
Reputation: 10958
You should pass cascade='delete'
to the to_user
relationship()
. See the docs here.
The ondelete
argument to ForeignKey
affects the generation of DDL statements, not how the ORM behaves.
Upvotes: 3