Chobeat
Chobeat

Reputation: 3535

how to access list of keys for a relationship in SQLAlchemy?

This is my code at the moment. I have a table, with a one-to-many relationship that works fine. I would like to access the list of the keys in the relationship: I can do this with a dedicated query but I would rather stick to the declarative logic and have a field like order_ids that "maps" from orders to their ids. Is it possible or do I have to write a dedicated select? What's the cleanest way to achieve this?

class Delivery(Base):
   __tablename__ = "delivery"
   ...
   id = sa.Column(GUID, primary_key=True, default=GUID_DEFAULT_SQLITE)
   orders = sa.orm.relationship("Order", lazy="subquery")
   order_ids = ???

class Order(Base):
    __tablename__ = "order"
    ...

    id = sa.Column(GUID, primary_key=True, default=GUID_DEFAULT_SQLITE)
    delivery_id = sa.Column(sa.ForeignKey("delivery.id"), nullable=True)
    delivery = sa.orm.relationship("Delivery", foreign_keys=[delivery_id], back_populates="orders")

Upvotes: 0

Views: 582

Answers (1)

kielni
kielni

Reputation: 4989

You've already defined the relationship from Delivery to Order with

orders = sa.orm.relationship("Order", lazy="subquery")

You can use this to access the order ids on an instance of Delivery with

order_ids = [order.id for order in delivery.orders]

If you really want this to look like a field on a Delivery object, you can use a @property decorator, and access it via deliver.order_ids:

class Delivery(Base):
    ...
    @property
    def order_ids(self) -> List[int]:
        return [order.id for order in self.orders]

Upvotes: 1

Related Questions