Форум сайта python.su
Хочу удалять каскадно поля в таблице M2M с обоих сторон.
Сперва добрался до рабочего варианта:
from sqlalchemy import Column, Integer, String, ForeignKey from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Association(Base): __tablename__ = 'exmp_association' parent_id = Column(Integer, ForeignKey('exmp_parent.id', ondelete='CASCADE'), primary_key=True) child_id = Column(Integer, ForeignKey('exmp_child.id', ondelete='CASCADE'), primary_key= extra_data = Column(String(50)) class Parent(Base): __tablename__ = 'exmp_parent' id = Column(Integer, primary_key=True) associations = relationship("Association", backref="parent") class Child(Base): __tablename__ = 'exmp_child' id = Column(Integer, primary_key=True) associations = relationship("Association", backref="child")
s = get_session() p = Parent() a = Association() c = Child() a.child = c p.associations.append(a) s.add(p) s.commit() a = s.query(Association).get([1, 1]) print(s.query(Parent).count()) print(s.query(Association).count()) print(a.parent) print(a.child) s.query(Parent).delete() s.commit() print(s.query(Parent).count()) print(s.query(Association).count())
class Association(Base): __tablename__ = 'exmp_association' parent_id = Column(Integer, ForeignKey('exmp_parent.id'), primary_key=True) child_id = Column(Integer, ForeignKey('exmp_child.id'), primary_key=True) extra_data = Column(String(50)) class Parent(Base): __tablename__ = 'exmp_parent' id = Column(Integer, primary_key=True) associations = relationship("Association", backref="parent", cascade='all, delete-orphan') class Child(Base): __tablename__ = 'exmp_child' id = Column(Integer, primary_key=True) associations = relationship("Association", backref="child", cascade='all, delete-orphan')
sqlalchemy.exc.IntegrityError: (IntegrityError) update or delete on table "exmp_parent" violates foreign key constraint "exmp_association_parent_id_fkey" on table "exmp_association" DETAIL: Key (id)=(1) is still referenced from table "exmp_association". 'DELETE FROM exmp_parent' {}
Отредактировано buddha (Июль 10, 2014 17:14:40)
Офлайн