Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I determine the type (e.g. many-to-one) of a dynamic SQLAlchemy 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 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?

like image 231
argentpepper Avatar asked Aug 09 '12 06:08

argentpepper


1 Answers

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.

like image 107
argentpepper Avatar answered Oct 04 '22 07:10

argentpepper