python - 如何从 SQLAlchemy 模型中确定子对象的类型?

标签 python sqlalchemy

我有以下 SQLAlchemy 模型:

class PersonConsent(ModelAbstract):
    __tablename__ = "personConsent"
    id = db.Column(db.Integer, primary_key=True)
    patientId = db.Column(db.Integer, db.ForeignKey("person.id"))
    authorizedPersonId = db.Column(db.Integer, db.ForeignKey("person.id"))
    attachmentId = db.Column(db.Integer)

    # Additional models
    authorizedPerson = db.relationship("Person", foreign_keys=[authorizedPersonId])
    consents = db.relationship("PersonConsentType", 
                secondary=personConsentToTypeMap,
                primaryjoin=id==personConsentToTypeMap.c.consentId,
                secondaryjoin=PersonConsentType.id==personConsentToTypeMap.c.consentTypeId)

仅给定 PersonConsent 模型,我如何确定构成 consents 字段的项目的模型?

例如,类似的东西

类型(PersonConsent.consents)== PersonConsentType

最佳答案

使用inspect 函数并遵循正确的属性以获得关系的目标模型。

from sqlalchemy import inspect

mapper = inspect(PersonConsent)
property = mapper.relationships['consents']
target = property.mapper.class_

assert target is PersonConsentType

从技术上讲,您可以通过执行 PersonConsent.consents.property.mapper.class_ 来实现这一点,但它不太通用。例如,您可以使用上面的检查来遍历所有关系,即使您不知道它们的名称。

关于python - 如何从 SQLAlchemy 模型中确定子对象的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27610618/

相关文章:

python - 通过 xml.dom.minidom 处理 RSS/RDF

python - AppEngine 上使用 Flask 的 SQLAlchemy Python : OperationalError: (_mysql_exceptions. 操作错误)(2004, "Can' t 创建 TCP/IP 套接字 (-1)")

python - SQLAlchemy:测试关系是否存在而不实际加载它

python - sqlalchemy中执行之前如何知道sql查询结果的类型

mysql - 服务器端的 SQLAlchemy 日期时间操作

python - 如何在Python中的无限循环中每X次调用一次函数?

就地for循环中的Python字符串连接?

python - 多个 wait_for_messages 想要discord.py

python - 如何在 python 中绘制概率质量函数

python - 使用 sqlalchemy 从类返回 NOT NULL 列