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

£可爱£侵袭症+ 提交于 2019-12-03 02:25:42
van

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
                )
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!