sqlalchemy: 'InstrumentedList' object has no attribute 'filter'

Question:

I have the following 3 classes:

class Resource:
    id = Column(Integer, primary_key=True)
    path = Column(Text)
    data = Column(Binary)
    type = Column(Text)

    def set_resource(self, path, data, type):
        self.path = path
        self.data = data
        self.type = type

class EnvironmentResource(Base, Resource):
    __tablename__ = 'environment_resources'
    parent_id = Column(Integer, ForeignKey('environments.id', ondelete='CASCADE'))
    def __init__(self, path, data, type):
        self.set_resource(path, data, type)

class Environment(Base):
    __tablename__ = 'environments'
    id = Column(Integer, primary_key=True)
    identifier = Column(Text, unique=True)
    name = Column(Text)
    description = Column(Text)

    _resources = relationship("EnvironmentResource",
        cascade="all, delete-orphan",
        passive_deletes=True)
    _tools = relationship("Tool",
        cascade="all, delete-orphan",
        passive_deletes=True)

    def __init__(self, name, identifier, description):
        self.name = name
        self.identifier = identifier
        self.description = description

    def get_resource(self, path):
        return self._resources.filter(EnvironmentResource.path==path).first()

On calling get_resource, I am told that ‘InstrumentedList’ object has no attribute ‘filter’ – I’ve gone through the documentation and can’t quite figure this out. What am I missing, so that I may be able to filter the resources corresponding to an environment inside my ‘get_resource’ method?

PS: I know get_resource will throw an exception, that’s what I’d like it to do.

Asked By: Liam M

||

Answers:

In order to work with the relationship as with Query, you need to configure it with lazy='dynamic'. See more on this in Dynamic Relationship Loaders:

_resources = relationship("EnvironmentResource",
    cascade="all, delete-orphan",
    lazy='dynamic',
    passive_deletes=True)
Answered By: van
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.