How to determine the type (e.g. many-to-one) of a SQLAlchemy dynamic relationship?

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 accessed the lazy query object as follows:

relation = getattr(Computer, 'owner')

How do you determine whether it refers relationto a single instance Person(ie, one-to-two relationships, as in this example), or if it relationrefers to a collection of instances (like a one-to-many relationship)? In other words, how can I determine the relationship type of a dynamic SQLAlchemy relationship object?

+5
source share
1 answer

, model = Computer relation = 'owner' , True , , :

model._sa_class_manager[relation].property.uselist

, , one() getattr(model, relation):

if model._sa_class_manager[relation].property.uselist:
    related_instances = getattr(model, relation)
else:
    related_instance = getattr(model, relation).one()

, , .

+2

All Articles