我有实体Client
,它与实体Address
有一对多的关系。
Address
列type
,可以是primary(int 1)或secondary(int 2)。
我可以通过client.addresses == [...]
访问客户端地址
现在我可以创建一对一的访问器,例如:
client.primary_address == Address(...)
女巫会用额外的JOIN来评估加入arg:ON (client.id == address.client_id and address.type = 1)
?
答案 0 :(得分:0)
关注Specifying Alternate Join Conditions
文档,您可以执行以下操作:
class Client(Base):
__tablename__ = "client"
client_id = Column(Integer, primary_key=True)
# ...
addresses = relationship(Address, ...)
primary_address = relationship(Address, uselist=False,
primaryjoin = and_(Address.client_id == client_id, Address.type == 1),
)
secondary_address = relationship(Address, uselist=False,
primaryjoin = and_(Address.client_id == client_id, Address.type == 2),
)
这将允许您访问(读取)主地址和辅助地址,就好像它是1-1关系一样。您可以像下面那样设置(写入)事件:
my_client.primary_address = Address(type=1, ...)
但您必须确保地址具有type
列的正确值(1或2),这似乎是技术领域。
旁注:type
是python中的保留字。