Inconsistent sqlalchemy.exc.IntegrityError

Viewed 53
class Parent():  

    id = Column(Integer ,primary_key = true)  
    children = relationship('Child', back_populates='parent', passive_deletes =True) 
    dependents = relationship('Dependent', back_populates='parent', passive_deletes =True)


class Child():  

   id = Column(Integer , primary_key = true)
   parent = relationship('Parent', back_populates='children')
   parent_id = Column(Integer, ForeignKey('parent.id', ondelete='CASCADE') 
   anothers = relationship('Another', back_populates='child') 


class Dependent():  

   id = Column(Integer , primary_key = true)
   parent = relationship('Parent', back_populates='children')
   parent_id = Column(Integer, ForeignKey('parent.id', ondelete='CASCADE') 
   another = relationship('Another', back_populates='dependent', uselist=False, passive_deletes = True) 


class Another():
   id = Column(Integer , primary_key = true)
  dependent = relationship('Dependent', back_populates='anothers')
  dependent_id = Column(Integer, ForeignKey('dependent.id', ondelete='CASCADE') 
  child = relationship('Child', back_populates='another')
  child_id = Column(Integer, ForeignKey('child.id')) 

When I delete child object, child field of Another gets being null. That's how it should be. Another should be deleted if only dependent class object removed. I should assume if I delete the parent object, everything under it should be removed. Both dependent objects, children objects and another objects as well( because it has ondelete cascade relation with the dependent , and dependent has ondelete cascade with the parent)

When I delete parent object, the error is throwing this message:

sqlalchemy.exc.IntegrityError: update or delete on table "child" violates foreign key constraint "another_child_id_fkey" on table "another" DETAIL: Key (id)=(4) is still referenced from table "another".

when I delete child object, no problem for another class. why I get this error?

0 Answers
Related