SQLAlchemy声明性mixin类与declared_attr的自引用外键关系

时间:2018-06-05 09:47:16

标签: python sqlalchemy self-referencing-table

我有一个mixin类,我在SQLAlchemy应用程序的开头附近定义,然后继承几乎我使用的每个声明性模型。

class Owned(object):

    @declared_attr
    def created_by_id(cls):
        return Column(Integer, ForeignKey("accounts.id"),
            nullable = True)

    @declared_attr
    def created_by(cls):
        return relationship("Account", foreign_keys = cls.created_by_id)

    @declared_attr
    def updated_by_id(cls):
        return Column(Integer, ForeignKey("accounts.id"),
            nullable = True)

    @declared_attr
    def updated_by(cls):
        return relationship("Account", foreign_keys = cls.updated_by_id)

这适用于大多数预期的用例。

class Thing(Owned, Base): # Base is from SQLAlchemy's declarative_base()
    pass

account = session.query(Account).first()

thing = Thing(created_by = account, updated_by = account)

session.add(thing)
session.commit()
session.refresh(thing)

assert thing.created_by == account # pass
assert thing.updated_by == account # pass

但是,当我将Account本身定义为继承自Owned时,我会遇到意外行为。

class Account(Owned, Base):
    pass

account_old = session.query(Account).first()

account_new = Account(created_by = account_old, updated_by = account_old)

session.add(account_new)
session.commit()
session.refresh(account_new)

assert account_new.created_by_id == account_old.id # pass
assert account_new.updated_by_id == account_old.id # pass

# BUT!

assert account_new.created_by == account_old # fail
assert account_new.updated_by == account_old # fail

account_new.created_by # []
account_new.updated_by # []

我看到,在这种情况下,我已将created_by_idupdated_by_id转换为自引用外键。但是,我不明白的是,SQLAlchemy没有使用预期的relationship实例填充关联的Account列。

我做错了什么?

1 个答案:

答案 0 :(得分:0)

adjacency list relationship"方向"默认情况下假定为一对多。使用remote_side指令确定关系是多对一的,这就是你之后的关系:

def _create_relationship(cls, foreign_keys):
    kwgs = {}
    # Bit of a chicken or egg situation:
    if cls.__name__ == "Account":
        kwgs["remote_side"] = [cls.id]

    return relationship("Account", foreign_keys=foreign_keys, **kwgs)


class Owned:

    @declared_attr
    def created_by_id(cls):
        return Column(Integer, ForeignKey("accounts.id"),
            nullable = True)

    @declared_attr
    def created_by(cls):
        return _create_relationship(cls, cls.created_by_id)

    @declared_attr
    def updated_by_id(cls):
        return Column(Integer, ForeignKey("accounts.id"),
            nullable = True)

    @declared_attr
    def updated_by(cls):
        return _create_relationship(cls, cls.updated_by_id)