如何使用sqlalchemy通过额外的连接参数从一对多创建一对一访问器?

时间:2014-04-13 14:36:10

标签: python sqlalchemy

我有实体Client,它与实体Address有一对多的关系。 Addresstype,可以是primary(int 1)或secondary(int 2)。

我可以通过client.addresses == [...]访问客户端地址 现在我可以创建一对一的访问器,例如: client.primary_address == Address(...)女巫会用额外的JOIN来评估加入arg:ON (client.id == address.client_id and address.type = 1)

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中的保留字。