[英]How to determine the type of a child object from the SQLAlchemy model?
I have the following SQLAlchemy model: 我有以下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)
Given just the PersonConsent model how do I determine the model of items that make up the consents
field? 仅给出PersonConsent模型,我如何确定组成consents
字段的项目的模型?
For example, something like 例如,类似
type(PersonConsent.consents) == PersonConsentType
Use the inspect
function and follow the correct attributes to get the target model for a relationship. 使用inspect
功能并遵循正确的属性来获取关系的目标模型。
from sqlalchemy import inspect
mapper = inspect(PersonConsent)
property = mapper.relationships['consents']
target = property.mapper.class_
assert target is PersonConsentType
You can technically get to this by doing PersonConsent.consents.property.mapper.class_
, but it's less general. 从技术PersonConsent.consents.property.mapper.class_
,您可以通过执行PersonConsent.consents.property.mapper.class_
来做到这PersonConsent.consents.property.mapper.class_
,但这不太普遍。 You could use the inspection above to, for example, loop over all the relationships, even if you don't know their names. 例如,即使您不知道它们的名称,也可以使用上面的检查来遍历所有关系。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.