I have entity Client
, it has one-to-many relation to entity Address
. Address
has column type
, witch can be primary (int 1) or secondary (int 2).
I can access client addresses through client.addresses == [...]
Now can I create accessors witch would act as one-to-one, eg: client.primary_address == Address(...)
witch would evaluate to JOIN with extra JOIN arg: ON (client.id == address.client_id and address.type = 1)
?
Following Specifying Alternate Join Conditions
documentation, you can do:
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),
)
This will allow you to access (read) both primary and secondary addresses as if it were 1-1 relationship. You can event set (write) it like below:
my_client.primary_address = Address(type=1, ...)
but you will have to ensure that the Address has proper value (1 or 2) for the type
column which seems to be a technical field.
Side remark: type
is reserved word in python.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments