Let's say I have the following relation:
Reference(slide_id, group_id)
where reference is the association of a slide and a group.
One slide can be used in many references (with a different group): primary key is slide_id
+ group_id
, which must be unique.
I want to have all the references deleted when either of the pointed group or slide are deleted. Which I do by adding a cascade in the backref of the relationship:
# definition of Reference model
slide = db.relationship(
Slide,
backref=db.backref('references', cascade='all, delete, delete-orphan')
)
group = db.relationship(
Group,
backref=db.backref('references', cascade='all, delete, delete-orphan')
)
I also want to have the referenced group or slide deleted, whenever I delete a reference and there are no other references that use said group and/or slide.
I have thought about using @listens_for(Reference, 'after_delete')
to manually delete parents when needed. I also tried attribute combos in the relationship, but I am not really sure how to solve this problem.
I think that idea with
@listens_for
is not bad. You need just listen forReference
before_delete
. Below is an example that can help.Let's check it:
You will see that in first case
Preference
,Group
andSlide
were deleted. Because otherPreference
’s didn't related toGroup
andSlide
. But in the second case you will see that onlyPreference
was removed:Hope this helps.