我编写了一个SQLAlchemy应用程序,它由一个“后端”和一个“前端”组成(后端是一个填充数据库的服务,前端是一个呈现该数据的WSGI web应用程序)
前端和后端都导入一个公共模块(“模型”),其中包含SQLAlchemy ORM类定义,而不包含其他内容。在前端和后端,我定义了ORM基类的子类,这些子类添加了方法来完成应用程序的实际工作。我发现这是一个优雅而干净的解决方案,可以将普通事物(数据库结构)与具体事物(数据输入和检索)分开
然而,这显然破坏了SQLAlchemy的关系,这些关系在“模型”模块中定义,因此不知道派生类及其方法。下面是一个例子
所以我的问题是:如何向ORM(子)类添加特定于模块的方法,并且仍然使用SQLAlchemy的关系
models.py
# pure SQLAlchemy ORM declarations, imported by various modules
class JobT(Base):
id = Column(Integer, primary_key=True)
tool = relationship('ToolT', back_populates="jobs", uselist=False)
class ToolT(Base):
id = Column(Integer, primary_key = True)
jobs = relationship('JobT', back_populates="tool")
backend.py
# defines derived classes that add actual functionality to the objects
from models import ToolT, JobT
class Tool(ToolT):
def fancy_method(self):
pass
class Job(JobT):
def do_stuff(self):
foo = self.tool.fancy_method()
>>> job = Job(...)
>>> job.do_stuff()
AttributeError: 'ToolT' object has no attribute 'do_stuff'
(我知道为什么会发生这种错误。无需解释)
目前没有回答
相关问题 更多 >
编程相关推荐