Johnny G Johnny G - 13 days ago 6
Python Question

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

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.

van van
Answer

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)