我有以下 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/