【发布时间】:2014-05-23 07:48:28
【问题描述】:
编辑
问题在于导入。我应该做的是写:from SomeInterface import SomeInterface。真的,我应该按照Python styleguide (PEP 8) 用小写someinterface.py 写模块名称。
我有一个文件model.py,它定义了与我的数据库相关的所有类以及实例化我的 Base。
# model.py
metadata = MetaData()
DeclarativeBase = declarative_base()
metadata = DeclarativeBase.metadata
class Bar(DeclarativeBase):
__tablename__ = 'Bar'
__table_args__ = {}
# column and relation definitions
文件model.py 是自动生成的,所以我无法真正触摸它。我所做的是创建一个名为 modelaugmented.py 的文件,我在其中通过继承向一些模型类添加了额外的功能。
# modelaugmented.py
from model import *
import SomeInterface
class BarAugmented(Bar, SomeInterface):
pass
# SomeInterface.py
class SomeInterface(object):
some_method(): pass
我遇到的问题是,对于像 BarAugmented 这样的类,我收到以下错误:
TypeError: Error when calling the metaclass bases
metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases
只有当SomeInterface 在单独的文件中而不是在modelaugmented.py 中时,我才会收到此错误。
我知道SomeInterface 和Bar 的元类是不同的。问题是我不知道如何解决这个问题。我尝试了Triple inheritance causes metaclass conflict... Sometimes 中建议的解决方案,该解决方案适用于给出的示例,但不适用于我的情况。不确定 SqlAlchmey 是否与它有关。
class MetaAB(type(DeclarativeBase), type(SomeInterface)):
pass
class BarAugmented(Bar, SomeInterface):
__metaclass__ = MetaAB
然后我得到错误:
TypeError: Error when calling the metaclass
bases multiple bases have instance lay-out conflict
使用 SQLAlchemy 0.8 和 Python 2.7。
【问题讨论】:
-
是的...您正面临多重继承问题。还有一个问题......在
BarAugmented,它必须将数据保存到的__table__是什么?表foo?表bar?你真的需要这种类型的模式吗? (只是问,但对于任何 ORM 来说,它看起来都是一个非常复杂的结构来正确处理) -
@BorrajaX 非常公平。我编辑了我的问题。
-
MHmm... 看来问题不在 SqlAlchemy... 看看这个:stackoverflow.com/questions/6557407/… 和 code.activestate.com/recipes/… (我刚刚找到那些链接,我不知道是否他们会很有帮助)你能试试非声明性声明吗? (只需声明你的表,然后是你的类,然后是你的映射)?
-
@BorrajaX 感谢您的链接。我之前尝试过,但不幸的是我收到了错误
'SomeInterface' has no attribute '_decl_class_registry'。 -
很抱歉 :-( 那么我会选择非声明式的。使用声明式模型可能会改变你的班级
__metaclass__(但请等待真正的答案,虽然......你可能不需要这样做)
标签: python sqlalchemy