'in many-to-many relationships, can you delete a row from one table without deleting any rows from the second table?
I am creating a database & working on CRUD functions. I've run into a problem with the Delete functionality.
I have two tables, connected in a many-to-many relationship via an association table. I want to delete a row from only one of the tables. And presumably I will also have to remove the rows in the association table mentioning this row. But I don't want to delete anything from the other table.
For example, using one of the examples of many-to-many I've seen, (Students & Classes):
There is a table of students, Students. There is a table of classes, Classes. Each student is linked to multiple classes. Each class is linked to multiple students.
The Students and Classes tables are linked via an association table StudentsvsClasses.
Suppose one student drops out of university. I want to drop this student from Students, and links to all their classes (listed in StudentsvsClasses). However, I don't want to delete any rows in Classes. Because these classes still exist, and are associated with other students.
How can I implement this? Is it even possible? I'm new to this and am unable to find an example. Most examples I have found (Parents & Children examples) involve: deleting a parent from the Parent table, and also deleting all associated children from the Children table.
If anyone can point me to an example of this online, or can help out, it would be greatly appreciated. Please let me know if my wording was unclear, or if I can clarify anything. I'd appreciate any and all help with this. Thanks!
Here's the code of my toy example – the models.py file:
StudentsvsClasses = Table('StudentsvsClasses',
Base.metadata,
Column('student_key', String, ForeignKey('students.student_id')),
Column('class_key', String, ForeignKey('classes.class_id'))
)
class Students(Base):
__tablename__ = "students"
student_id = Column(String, unique=True, primary_key=True, nullable=False)
student_name = Column(String, nullable=False)
associated_classes = relationship(
"Classes",
secondary=StudentsvsClasses,
back_populates="associated_students"
)
class Classes(Base):
__tablename__ = "classes"
class_id = Column(String, unique=True, primary_key=True, nullable=False)
class_name = Column(String, nullable=False)
associated_students = relationship(
"Students",
secondary=StudentsvsClasses,
back_populates="associated_classes"
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|