SQLAlchemy chaining association proxy for great grandchildren?

别等时光非礼了梦想. 提交于 2019-12-04 02:53:37

Given that those are for retrieval and view only (as you mentioned in the comment, adding would be ambiguous), I would rather do a viewonly relationship without an association_proxy:

class Group(db.Model):
    # ...
    toys = relationship('Toy',
        secondary="join(Group, Parent, Group.id == Parent.group_id).join(Child, Parent.id == Child.parent_id)",
        primaryjoin="and_(Group.id == Parent.group_id, Parent.id == Child.parent_id)",
        secondaryjoin="Child.id == Toy.child_id",
        viewonly=True,
    )

Note that this is a new feature of SQLAlchemy and is describe in the Composite “Secondary” Joins section of the documentation.

Then you can use it just for query:

group_id = 123
group = session.query(Group).get(group_id)
print(group.toys)

Or you can even use it to filter, so to find a group which contains a toy with name "Super Mario" you can do:

group = session.query(Group).filter(Group.toys.any(Toy.name == "Super Mario"))

But in reality all this you can do with simple query, or create a query-enabled property. See Customizing Column Properties section of the documentation, where you can use any of the simple property, column_property or hybrid attribute.

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