我有一个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_id
和updated_by_id
转换为自引用外键。但是,我不明白的是,SQLAlchemy没有使用预期的relationship
实例填充关联的Account
列。
我做错了什么?
答案 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)