简体   繁体   中英

How does flask sql alchemy cascade delete work?

Hi I am having a very hard time in figuring out the cascade delete. It just isn't working.

I have two tables Students and Enrollments. Student has details of student and Enrollments has details of student ID (FK) and course ID(FK) which stores all the courses student has enrolled into.

class Student(db.Model):
__tablename__ = 'student'
student_id = db.Column('student_id', db.Integer, primary_key=True, autoincrement=True)
roll_number = db.Column('roll_number',db.String, nullable=False,unique=True)
first_name = db.Column('first_name', db.String,nullable=False)
last_name=db.Column('last_name',db.String)


class Enrollments(db.Model):
__tablename__ = "enrollments"
enrollment_id = db.Column("enrollment_id", db.Integer, autoincrement=True, primary_key=True)
estudent_id = db.Column("estudent_id",db.Integer,db.ForeignKey("student.student_id"),nullable=False)
ecourse_id = db.Column("ecourse_id", db.Integer,db.ForeignKey("course.course_id"),nullable=False)

How do I add cascade delete such that if I delete any student in the student table it should delete all the enrollments associated with the student in the enrollments table? If you can modify my code so that the above would work I would be grateful to you. If you can explain it as well I 'd be indebted. I am learning Flask-SQLAlchemy.

One way I've done this is by using the cascade="all, delete" attribute. In your case, you would have to add this line to your 'Student' model:

enrollments = db.relationship('Enrollments', cascade="all, delete")

This defines a relationship with the 'Enrollments' model that will delete any tables created underneath the student. See here for more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM