Suppose I have the following SQLAlchemy classes defined:
Base = declarative_base()
class Person(Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
computers = relationship('Computer', backref=backref('owner', lazy='dynamic'))
class Computer(Base):
__tablename__ = 'computer'
id = Column(Integer, primary_key=True)
ownerid = Column(Integer, ForeignKey('person.id'))
Suppose further that I have accessed the lazy query object this way:
relation = getattr(Computer, 'owner')
How can I determine if relation refers to a single instance of Person (that is, in a many-to-one relationship, like in this example), or if relation refers to a collection of instances (like in a one-to-many relationship)? In other words, how can I determine the relationship type of a dynamic SQLAlchemy relationship object?
If we suppose model = Computer and relation = 'owner' as in the question, then the following attribute is True if and only if the relation is a list of instances as opposed to a single instance:
model._sa_class_manager[relation].property.uselist
You can then use this to test whether or not to call the one() method on the result of getattr(model, relation):
if model._sa_class_manager[relation].property.uselist:
related_instances = getattr(model, relation)
else:
related_instance = getattr(model, relation).one()
I am not confident, however, that this is the best solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With