在SQLAlchemy中删除父项后删除子项

时间:2012-09-29 15:04:29

标签: python sqlalchemy

我的问题如下:

我在SQLAlchemy中通过多对多关系链接了两个模型EntryTag。现在,我希望在删除Tag后删除没有任何相应Entry的每个Entry

示例说明我想要的内容:

    标有Entry 1python

  • java 标有Entry 2python

  • c++

使用这两个条目,数据库包含标记pythonjavac++。如果我现在删除Entry 2我希望SQLAlchemy自动从数据库中删除c++标记。是否可以在Entry模型本身中定义此行为,还是有更优雅的方式?

感谢。

2 个答案:

答案 0 :(得分:2)

这个问题在这里被问了一段时间:Setting delete-orphan on SQLAlchemy relationship causes AssertionError: This AttributeImpl is not configured to track parents

这是“多对多的孤儿”问题。 jadkik94很接近你应该使用事件来捕获它,但我尝试建议不要在mapper事件中使用Session,尽管它适用于这种情况。

下面,我从其他SO问题逐字逐句回答,并将“Role”替换为“Entry”:

from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import event
from sqlalchemy.orm import attributes

Base= declarative_base()

tagging = Table('tagging',Base.metadata,
    Column('tag_id', Integer, ForeignKey('tag.id', ondelete='cascade'), primary_key=True),
    Column('entry_id', Integer, ForeignKey('entry.id', ondelete='cascade'), primary_key=True)
)

class Tag(Base):

    __tablename__ = 'tag'
    id = Column(Integer, primary_key=True)
    name = Column(String(100), unique=True, nullable=False)

    def __init__(self, name=None):
        self.name = name

class Entry(Base):
    __tablename__ = 'entry'

    id = Column(Integer, primary_key=True)
    tag_names = association_proxy('tags', 'name')

    tags = relationship('Tag',
                        secondary=tagging,
                        backref='entries')

@event.listens_for(Session, 'after_flush')
def delete_tag_orphans(session, ctx):
    # optional: look through Session state to see if we want
    # to emit a DELETE for orphan Tags
    flag = False

    for instance in session.dirty:
        if isinstance(instance, Entry) and \
            attributes.get_history(instance, 'tags').deleted:
            flag = True
            break
    for instance in session.deleted:
        if isinstance(instance, Entry):
            flag = True
            break

    # emit a DELETE for all orphan Tags.   This is safe to emit
    # regardless of "flag", if a less verbose approach is
    # desired.
    if flag:
        session.query(Tag).\
            filter(~Tag.entries.any()).\
            delete(synchronize_session=False)


e = create_engine("sqlite://", echo=True)

Base.metadata.create_all(e)

s = Session(e)

r1 = Entry()
r2 = Entry()
r3 = Entry()
t1, t2, t3, t4 = Tag("t1"), Tag("t2"), Tag("t3"), Tag("t4")

r1.tags.extend([t1, t2])
r2.tags.extend([t2, t3])
r3.tags.extend([t4])
s.add_all([r1, r2, r3])

assert s.query(Tag).count() == 4

r2.tags.remove(t2)

assert s.query(Tag).count() == 4

r1.tags.remove(t2)

assert s.query(Tag).count() == 3

r1.tags.remove(t1)

assert s.query(Tag).count() == 2

两个几乎完全相同的SO问题使其成为手头的东西,因此我已将其添加到http://www.sqlalchemy.org/trac/wiki/UsageRecipes/ManyToManyOrphan的wiki中。

答案 1 :(得分:1)

我会让代码代替我说:

from sqlalchemy import create_engine, exc, event
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import func, Table, Column, Integer, String, Float, Boolean, MetaData, ForeignKey
from sqlalchemy.orm import relationship, backref

# Connection
engine = create_engine('sqlite:///', echo=True)
Base = declarative_base(bind=engine)
Session = sessionmaker(bind=engine)

# Models
entry_tag_link = Table('entry_tag', Base.metadata,
    Column('entry_id', Integer, ForeignKey('entries.id')),
    Column('tag_id', Integer, ForeignKey('tags.id'))
)

class Entry(Base):
    __tablename__ = 'entries'
    id = Column(Integer, primary_key=True)
    name = Column(String(255), nullable=False, default='')

    tags = relationship("Tag", secondary=entry_tag_link, backref="entries")

    def __repr__(self):
        return '<Entry %s>' % (self.name,)

class Tag(Base):
    __tablename__ = 'tags'
    id = Column(Integer, primary_key=True)
    name = Column(String(255), nullable=False)

    def __repr__(self):
        return '<Tag %s>' % (self.name,)

# Delete listener
def delete_listener(mapper, connection, target):
    print "---- DELETING %s ----" % (target,)
    print '-' * 20
    for t in target.tags:
        if len(t.entries) == 0:
            print ' ' * 5, t, 'is to be deleted'
            session.delete(t)
    print '-' * 20

event.listen(Entry, 'before_delete', delete_listener)

# Utility functions
def dump(session):
    entries = session.query(Entry).all()
    tags = session.query(Tag).all()

    print '*' * 20
    print 'Entries', entries
    print 'Tags', tags
    print '*' * 20


Base.metadata.create_all()

session = Session()

t1, t2, t3 = Tag(name='python'), Tag(name='java'), Tag(name='c++')

e1, e2 = Entry(name='Entry 1', tags=[t1, t2]), Entry(name='Entry 2', tags=[t1, t3])

session.add_all([e1,e2])
session.commit()

dump(session)

raw_input("---- Press return to delete the second entry and see the result ----")

session.delete(e2)
session.commit()

dump(session)

上面的代码使用SQLAlchemy ORM事件的after_delete event。这条线具有魔力:

event.listen(Entry, 'before_delete', delete_listener)

这表示要收听Entry项目的所有删除,并打电话给我们的听众,这将做我们想要的。但是,文档不建议更改事件内的会话(请参阅我添加的链接中的警告)。但据我所见,它确实有效,所以由你来决定这是否适合你。