Considering the following MRE:
from sqlalchemy import ForeignKey
from sqlalchemy.orm import DeclarativeBase
from sqlalchemy.orm import Mapped
from sqlalchemy.orm import mapped_column
from sqlalchemy.orm import relationship
class Base(DeclarativeBase):
pass
class Item(Base):
__tablename__ = "item"
id: Mapped[int] = mapped_column(primary_key=True)
box_id: Mapped["Box"] = mapped_column(ForeignKey("box.id"))
owner_id: Mapped["Owner"] = mapped_column(ForeignKey("owner.id"))
box: Mapped["Box"] = relationship(back_populates="items")
owner: Mapped["Owner"] = relationship(back_populates="items")
class Box(Base):
__tablename__ = "box"
id: Mapped[int] = mapped_column(primary_key=True)
items: Mapped[list["Item"]] = relationship()
class Owner(Base):
__tablename__ = "owner"
id: Mapped[int] = mapped_column(primary_key=True)
items: Mapped[list["Item"]] = relationship()
# association proxy/hybrid property here
…at the last line (commented) I’d like some way to access a list of unique Box
es for each Owner
.
If I add the following association proxy to class Owner
:
boxes: AssociationProxy[list["Box"]] = association_proxy("items", "box")
… this partially adresses the goal, though the list is not unique len(boxes) == len(items)
.
To only return unique Box
es, I can add the following hybrid property:
@hybrid_property
def unique_boxes(self):
return list(set(self.boxes))
… or any other “uniquifying” function run on the association proxy boxes
.
Is there a more graceful way to achieve this outcome? Perhaps one which doesn’t require the intermediary association proxy?