python - SQLAlchemy:从 db.Model 获取关系

标签 python sqlalchemy

我需要获取模型的属性列表,这些属性实际上是关系(也就是说,它们是由 relationship() 创建的)。

假设我在 models 中有一个模型 Foo:

class Thing(db.Model):
    id = db.Column(...)
    bar_id = db.Column(...)
    foo_id = db.Column(...)
    foo = db.relationship('Foo')
    bar = db.relationship('Bar')

稍后,我想采用 models.Thing 并获取关系属性列表,即 ['foo', 'bar']

目前我正在检查 dir(models.Thing) 指示的每个属性恰好是类型 sqlalchemy.orm.attributes.InstrumentedAttribute 的类property 属性 — 可以是 ColumnPropertyRelationshipProperty。这样就可以了,但我想知道是否还有其他方法。

我可能只找到所有以 _id 结尾的属性并导出关系名称,但在某些情况下这可能会中断。

如何设置 __relationships__ = ['foo', 'bar']

或者 SQLAlchemy 中是否有内置的东西可以帮助我?

最佳答案

确实有-看看sqlalchemy.inspection.inspect .在映射类(例如,您的 Thing 类)上调用 inspect 将返回 Mapper ,它有一个 relationships dict 的属性如下:

from sqlalchemy.inspection import inspect

thing_relations = inspect(Thing).relationships.items()

关于python - SQLAlchemy:从 db.Model 获取关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21206818/

相关文章:

python - 在 Python 和 linux 中如何获取给定的用户 ID

python - 在 AKS 上部署 python docker 镜像会出现 "exec/usr/bin/sh: exec format error"

python - GDAL Python 创建轮廓线

python - Pandas DataFrame iloc 破坏了数据类型

python - SQLAlchemy 属性错误 : 'NoneType' object has no attribute '_getter'

python - sqlalchemy connection.execute() 上的 UnicodeDecodeError 用于选择查询

python - SQLAlchemy 中的数据透视表

python - NLTK:包错误?朋克和泡菜?

python - 如何高效地将混合类型的 pandas DataFrame 加载到 Oracle DB 中

python - 如何设置 PasswordType 属性的值?