Thiago
Thiago

Reputation: 724

delete one-to-one relationship in flask

I'm currently developing an application using flask and I'm having a big problem to delete items in an one-to-one relationship. I have the following structure in my models:

class User(db.Model):
   __tablename__ = 'user'
   user_id = db.Column(db.String(8), primary_key = True)
   password = db.Column(db.String(26))

class Student(db.Model):
   __tablename__ = 'student'
   user_id = Column(db.String(8), ForeignKey('user.user_id'), primary_key = True)
   user = db.relationship('User')

class Professor(db.Model):
   __tablename__ = 'professor'
   user_id = Column(db.String(8), ForeignKey('user.user_id'), primary_key = True)
   user = db.relationship('User')

What I want to do is delete the Student or the Professor if I delete the user. I have tried to test it using the code below, however, when I check my database, the student and professor are still there and my tests don't pass. I tried to include the cascade parameter when I set the relationship but it doesn't work. I have found in the internet to use this parameter: single_parent=True, but it also doesn't work.

user1 = User(user_id='user1234',password='alsdjwe1')
user2 = User(user_id='user2345',password='asfr5421')
student1 = Student(user = user1)
professor1 = Professor(user = user2)
db.session.delete(user1)
db.session.delete(user2)

I'd be glad if somebody can help me with this.

Thank you very much,

Thiago.

Upvotes: 2

Views: 1102

Answers (1)

Eric Workman
Eric Workman

Reputation: 1445

Use the cascade argument in your relationships.

class Student(db.Model):
    __tablename__ = 'student'
    user_id = Column(db.String(8), ForeignKey('user.user_id'), primary_key = True)
    user = db.relationship('User', cascade='delete')

class Professor(db.Model):
    __tablename__ = 'professor'
    user_id = Column(db.String(8), ForeignKey('user.user_id'), primary_key = True)
    user = db.relationship('User', cascade='delete')

You might want to look into delete-orphan if your use case needs it.

Upvotes: 1

Related Questions