我有以下3个班级:
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()
在调用get_resource时,我被告知'InstrumentedList'对象没有属性'filter' - 我已经阅读了文档并且无法解决这个问题。我缺少什么,以便我可以过滤与'get_resource'方法中的环境相对应的资源?
PS:我知道get_resource会抛出异常,这就是我希望它做的事情。
答案 0 :(得分:53)
要使用与Query
一样的relationship,您需要使用lazy='dynamic'
对其进行配置。有关详情,请参阅Dynamic Relationship Loaders:
_resources = relationship("EnvironmentResource",
cascade="all, delete-orphan",
lazy='dynamic',
passive_deletes=True)