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

时间:2014-12-22 21:21:45

标签: 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字段的项目模型?

例如,像

type(PersonConsent.consents) == PersonConsentType

1 个答案:

答案 0 :(得分:4)

使用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_来实现这一点,但它不那么通用。您可以使用上面的检查,例如,循环所有关系,即使您不知道他们的名字。

相关问题