1

I have the following SQLAlchemy model:

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?

For example, something like

type(PersonConsent.consents) == PersonConsentType

1 Answer 1

4

Use the inspect function and follow the correct attributes to get the target model for a relationship.

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. You could use the inspection above to, for example, loop over all the relationships, even if you don't know their names.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.