问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/24970594/delete-one-to-one-relationship-in-flask