在SQLAlchemy中获取相关模型

2024-10-02 04:36:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我在SQLAlchemy中链接了各种模型(有很多,属于,等等)。有没有一种方法可以在给定的实例中找到相关的模型?在

比如:

usersModelInstance.getRelatedTables() // This should provide an array or something with the related tables of users (orders, logins, posts, etc.).

Tags: or实例方法模型ansqlalchemy链接with
1条回答
网友
1楼 · 发布于 2024-10-02 04:36:38

我不太确定你想要一个表列表还是一个映射类列表?在

无论哪种情况,首先为映射的对象构建一个属性列表:

# Import sqlalchemy so we can use it
import sqlalchemy as sa

# Rename the OP's object to `obj`
obj = usersModelInstance

# Build a list of only relationship properties
relation_properties = filter(
    lambda p: isinstance(p, sa.orm.properties.RelationshipProperty),
    sa.orm.object_mapper(obj).iterate_properties
)

请注意,如果不使用sa.orm.class_mapper(cls)函数,则可以使用该函数 当前有一个实体实例的句柄,但只有一个映射类。在

现在,在第一种情况下,您需要相关表的列表,请执行以下操作:

^{pr2}$

在第二种情况下,您可能需要相关映射类的列表, 执行:

related_classes = [prop.mapper.class_ for prop in relation_properties]

希望这能让你开始。在

相关问题 更多 >

    热门问题