使用连接表继承时,Mixin 被添加到每个子类表中
我有以下设置:
class Attribute(object):
a = Column(Integer)
class Thing(Base, Attribute):
b = Column(Integer)
class Subthing(Thing):
c = COlumn(Integer)
但是,Thing 和 Subthing 都将具有 Attribute mixin,这意味着它们都将具有 Attribute 中指定的列:
Thing: a | b
Subthing: a | c
我只希望这些 mixin 列出现在 Thing 而不是 Subthing 中:
Thing: a | b
Subthing: c
这可能吗?手动创建列和方法而不是对每个事物使用混合?
I have the following setup:
class Attribute(object):
a = Column(Integer)
class Thing(Base, Attribute):
b = Column(Integer)
class Subthing(Thing):
c = COlumn(Integer)
However, both Thing and Subthing will have the Attribute mixin, meaning they'll both have the columns specified in Attribute:
Thing: a | b
Subthing: a | c
I only want these mixin columns present in Thing and not Subthing:
Thing: a | b
Subthing: c
Is this possible or will I have to resort to making columns and methods manually instead of using a mixin for every Thing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Subthing
根据继承的定义从父级获取a
。如果您不想要这种行为,则Subthing
无法从该对象继承。一个可能的解决方案是引入另一个基类。那么Subthing只有
c
列,而Thing有a
和b
。Subthing
getsa
from the parent by definition of inheritance. If you don't want that behavior, thenSubthing
cannot inherit from that object. A possible solution is to introduce yet another base class.Then Subthing only has column
c
, and Thing hasa
, andb
.这是一种行为不一致,是由于 @declared_attr 的行为慢慢偏离仅针对“列复制”用例进行测试的行为契约而产生的。 “mixin 上的列”的原始用例是将其平等地应用于所有继承类,但是后来开发的 @declared_attr 没有采用这种行为,因此不一致。
将“列复制”更改为仅对非子类生效是向后不兼容的行为更改,因此仅在即将推出的 0.8 中如此。这是票证 #2565 (http://www.sqlalchemy.org/trac/ticket/2565),并在 r9baa197f2c67 中解决。
测试:
This is a behavioral inconsistency that's developed as the result from the behavior of @declared_attr slowly deviating from a behavioral contract that was only tested against the "column copy" use case. The original use case of the "column on mixin" was to apply it to all inheriting classes equally, however @declared_attr, which was developed a bit later, didn't adopt this behavior, hence inconsistent.
Changing "column copy" to only take effect for the non-subclass is a backwards-incompatible behavioral change, so is in the upcoming 0.8 only. This is ticket #2565 (http://www.sqlalchemy.org/trac/ticket/2565) and is resolved in r9baa197f2c67.
test:
我刚刚遇到了同样的问题。事实证明,如果您使用
@declared_attr
在 mixin 类中定义列,SQLAlchemy 就会正常运行。使用连接表继承时,直接在 mixin 中声明的列会泄漏到子类中。I just ran into the same issue. It turns out if you define columns in your mixin class using
@declared_attr
, SQLAlchemy behaves properly. Columns declared directly in the mixin leak into sub-classes when using joined-table inheritance.