How to specify table relationships in SQLAlchemy with multi-level/multiple joins?

前端 未结 1 842
一个人的身影
一个人的身影 2021-02-05 19:07

I\'m trying to define a relationship between two tables whose relations are indirect (i.e. through two other tables).

The results I\'m looking for can be fetched with th

相关标签:
1条回答
  • 2021-02-05 19:26

    In general, I would not define an indirect relationship as a relationship, because you risk these indirect relationships becoming out-of-sync when you make modifications. You might work-around some of these limitations by specifying the viewonly=False parameter for a relationship.

    A simpler, less risky, and more straight-forward solution would be to use a query (or query-enabled property) in case you would like to reload data from the database, and use python list comprehensions to get the sub-sub-children of the relationship tree:

    class Customer(Base):
        # ...
    
        @property
        def telnums_qry(self):
            sess = Session.object_session(self)
            return (sess.query(Telnum)
                    .join(Subscription)
                    .join(Account)
                    .filter(Account.user_id == self.id)
                    ).all()
    
    
        @property
        def telnums_mem(self):
            return [tel
                    for acc in self.accounts
                    for sub in acc.subscriptions
                    for tel in sub.telnums
                    ]
    
    
    class Telnum(Base):
        # ...
    
        @property
        def customer(self):
            return (self.subscription
                    and self.subscription.account
                    and self.subscription.account.customer
                    )
    
    0 讨论(0)
提交回复
热议问题