2014-12-22 118 views
1

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

回答

3

使用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_,但它不太普遍。您可以使用上面的檢查,例如,即使您不知道他們的名字,也可以使用所有的關係。

相關問題