桥接关系表的SQLAlchemy事件

时间:2019-03-04 22:47:39

标签: python sqlalchemy

我正在尝试跟踪对数据库的更改,而我目前正在尝试通过mapper事件进行更改。这对于标准表非常有用,但是对于多对多关系的桥表来说似乎并不可行。

例如,如果我有这些表

# Main Classes
class TblContacts(BaseRelationsTable):

    __tablename__ = 'tbl_contacts'
    __relationstable__ = TblContactsContacts
    _linkingtables__ = [TblEventsContacts, TblEiplContacts]
    __friendlyname__ = "Contact"

    guid = Column(String(36), primary_key=True)
    created = Column(SubTimeStamp)
    modified = Column(SubTimeStamp)
    username = Column(SubString)
    contact_type = Column(SubString)
    name_first = Column(SubString)
    name_last = Column(SubString)
    job_title = Column(SubString)
    company = Column(SubString)
    phone = Column(SubPhone)
    email = Column(SubEmail)
    address_line1 = Column(SubString)
    address_line2 = Column(SubString)
    address_city = Column(SubString)
    address_state = Column(SubString)
    address_zip = Column(SubString)
    address_country = Column(SubString)

    relations = orm.relationship('TblContacts',
                                 secondary='tbl_contacts_contacts',
                                 primaryjoin='TblContacts.guid==TblContactsContacts.parent_id',
                                 secondaryjoin='TblContacts.guid==TblContactsContacts.child_id',
                                 )

class TblContactsContacts(BaseTable):
    __tablename__ = "tbl_contacts_contacts"
    __friendlyname__ = "TblContactsContacts"

    guid = Column(SubUUID, primary_key=True, nullable=False, default=uuid.uuid4)
    parent_id = Column(String, ForeignKey('tbl_contacts.guid'))
    child_id = Column(String, ForeignKey('tbl_contacts.guid'))

这些映射器应用于这些表

def _after_insert(target):
    # Do Things
    pass

def _after_update(target):
    # Do Things
    pass

def _after_delete(target):
    # Do Things
    pass

由于代码的简单性,我宁愿继续使用after_insert,update ...,但我开始认为这行不通。

我是否必须使用before_commit来抓住它?如果可以,如何在会话中筛选记录以查找插入和更新的记录?

1 个答案:

答案 0 :(得分:0)

总结一下这个问题,我没有找到一种完全按照我在这个问题中所提出的方法进行操作的方法。我试图从会话提交事件中获取桥表记录,但这只为您提供了具有关系属性而不是桥表对象的父表记录。

因此,我最终只编写了触发器语句,并将其直接添加到数据库中。最后可能是一个更好的解决方案,但如果添加或减去数据库字段,它确实增加了另一个必须编辑的地方。