实例分配给关系时,sqlalchemy before_flush事件处理程序看不到外键的更改

时间:2018-07-17 08:31:20

标签: python sqlalchemy

我有一个before_flush事件监听器,用于检查员工的经理是否已更改。在这种情况下,将在EmpManHist表中自动创建一条记录。 manager是对Employee表的自引用。 这是我的表定义:

class Employee(Base):
    __tablename__ = 'employees'

    emp_id = Column(String, primary_key=True, unique=True)
    name = Column(String, nullable=False)
    manager_id = Column(String, ForeignKey('employees.emp_id'))
    direct_reports = relationship('Employee', backref=backref('manager', remote_side=[emp_id]))

当我通过直接修改ForeignKey(manager_id)将新经理分配给员工时,事件侦听器将正确地拾取它。但是当我执行实例分配时,它不会:

# this code does not pick up the manager_id change in the 'before_flush' event listener
emp2.manager = emp3
dal.session.add(emp2)
dal.session.commit()

# this does
emp2.manager_id = '1'
dal.session.add(emp2)
dal.session.commit()

那是为什么? 我正在使用python 3.6.3和sqlalchemy 1.1.13

下面是完整的工作示例:

from sqlalchemy import create_engine, Column, Integer, String, DateTime, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship, backref
from sqlalchemy import event
from sqlalchemy.orm.attributes import get_history
import datetime


Base = declarative_base()


class DataAccessLayer(object):

    def __init__(self):
        self.conn_string = conn_string
        self.engine = None
        self.session = None
        self.Session = None
        self.echo = True

    def connect(self):
        self.engine = create_engine(self.conn_string, echo=self.echo)
        Base.metadata.create_all(self.engine)
        self.Session = sessionmaker(bind=self.engine)


class Employee(Base):
    __tablename__ = 'employees'

    emp_id = Column(String, primary_key=True, unique=True)
    name = Column(String, nullable=False)
    manager_id = Column(String, ForeignKey('employees.emp_id'))
    direct_reports = relationship('Employee', backref=backref('manager', remote_side=[emp_id]))


class EmpManHist(Base):
    __tablename__ = 'emp_man_history'

    id = Column(Integer, primary_key=True)
    emp_id = Column(String, ForeignKey('employees.emp_id'))
    man_id_from = Column(String, ForeignKey('employees.emp_id'))
    man_id_to = Column(String, ForeignKey('employees.emp_id'))
    when = Column(DateTime, default=datetime.datetime.now)

    manager_from = relationship('Employee', foreign_keys=[man_id_from])
    manager_to = relationship('Employee', foreign_keys=[man_id_to])


conn_string = 'sqlite:///:memory:'
dal = DataAccessLayer()
dal.echo = True
dal.connect()
dal.session = dal.Session()


@event.listens_for(dal.session, 'before_flush')
def _emp_history_update(session, flush_context, instances):
    print("BEFORE FLUSH")
    for instance in session.dirty:
        if not isinstance(instance, Employee):
            continue
        man_hist = get_history(instance, 'manager_id')
        if man_hist.added:
            if man_hist.deleted:
                man_deleted = str(man_hist.deleted[0])
            else:
                man_deleted = None
            emp_man_hist = EmpManHist(emp_id=instance.emp_id, man_id_from=man_deleted,
                                      man_id_to=str(man_hist.added[0]))
            session.add(emp_man_hist)


emp1 = Employee(emp_id='1', name="AAA")
emp2 = Employee(emp_id='2', name="BBB", manager_id='1')
emp3 = Employee(emp_id='3', name="CCC", manager_id='1')


dal.session.add(emp3)
dal.session.flush()
dal.session.add(emp1)
dal.session.add(emp2)

dal.session.commit()

# this code does not pick up the manager_id change in the 'before_flush' event listener
emp2.manager = emp3
dal.session.add(emp2)
dal.session.add(emp3)
dal.session.commit()

# this does
emp2.manager_id = '1'
dal.session.add(emp2)
dal.session.commit()

1 个答案:

答案 0 :(得分:4)

当关系属性更改时,SQLAlchemy不会立即更新外键字段。因此,您的问题的答案是before_flush事件是在SQLAlchemy作为Employee操作的一部分更新flush实例的外键值之前触发的。

如果您专门自己更新manager_id属性,则在触发before_flush事件之前更改属性,这就是为什么您在_emp_history_update函数中看到更改的原因这种情况。

您仍可以使用after_flush事件来执行所需的所有操作,因为此时session.dirty尚未被清除。因此,我将您的事件监听器更改为:

@event.listens_for(session, 'after_flush')
def _emp_history_update(session, flush_context):
    for instance in session.dirty:
        if not isinstance(instance, Employee):
            continue
        man_hist = get_history(instance, 'manager_id')
        if man_hist.added:
            if man_hist.deleted:
                man_deleted = str(man_hist.deleted[0])
            else:
                man_deleted = None
            emp_man_hist = EmpManHist(emp_id=instance.emp_id, man_id_from=man_deleted,
                                      man_id_to=str(man_hist.added[0]))
            session.add(emp_man_hist)

这是测试代码:

emp1 = Employee(emp_id='1', name="AAA")
emp2 = Employee(emp_id='2', name="BBB", manager_id='1')
emp3 = Employee(emp_id='3', name="CCC", manager_id='1')

# I'm not using your DataAccessLayer object but that doesn't change anything
session.add_all([emp1, emp2, emp3])
# i've not explicitly called session.flush() as it's called by session.commit() anyway
session.commit()

# change the emp2's manager through relationship attribute
emp2.manager = emp3
# no need to re-add the Employee objects to the session
session.commit()

for change in session.query(EmpManHist).all():
    print(f'Employee {change.emp_id} changed to mgr_id {change.man_id_to}')

哪个输出:

Employee 2 changed to mgr_id 3

我注意到的另一件事是事件监听器的这一部分:

    if man_hist.added:
        if man_hist.deleted:
            man_deleted = str(man_hist.deleted[0])
        else:
            man_deleted = None
        emp_man_hist = EmpManHist(emp_id=instance.emp_id, man_id_from=man_deleted,
                                  man_id_to=str(man_hist.added[0]))
        session.add(emp_man_hist)

通过自己直接更改属性或更改manager_id关系属性来更改Employee实例的Employee.manager,切勿在{{1​​}}中显示实例。因此,您的man_hist.deleted实例的man_id_from属性始终为EmpManHist

这是从示例代码生成的NoneINSERT的日志,您可以从第二行的值列表中看到第二个值,该值与{ {1}}正在分配emp_man_hist

man_id_from