sqlalchemy将mixin列移到末尾
我有一个sqlalchemy模型,其中所有大多数表/对象都有一个notes字段。因此,为了遵循DRY原理,我将该领域移到了mixin类。
class NotesMixin(object):
notes = sa.Column(sa.String(4000) , nullable=False, default='')
class Service(Base, NotesMixin):
__tablename__ = "service"
service_id = sa.Column(sa.Integer, primary_key=True)
name = sa.Column(sa.String(255), nullable=False, index=True, unique=True)
class Datacenter(Base, NotesMixin):
__tablename__ = "datacenter"
datacenter_id = sa.Column(sa.Integer, primary_key=True)
name = sa.Column(sa.String(255), nullable=False, index=True, unique=True)
class Network(Base, NotesMixin, StatusMixin):
__tablename__ = "network"
network_id = sa.Column(sa.Integer, primary_key=True)
etc...
现在notes列是model /
db中的第一列。我知道它不会影响我的应用程序的功能,但是让我有点烦恼,请注意在id等之前看到注释。任何将其移到末尾的方法是什么?
-
找到了一个更清洁的解决方案:
sqlalchemy.ext.declarative.declared_attr
在sqlalchemy
0.6.5中使用装饰器(sqlalchemy.util.classproperty
在sqlalchemy <= 0.6.4中)class NotesMixin(object): @declared_attr def notes(cls): return sa.Column(sa.String(4000) , nullable=False, default='')
根据文档,这是“用于具有外键的列,以及需要目的地明确上下文的各种映射器级构造”。虽然严格来说不是这种情况,但它是通过在构造子类时调用方法(并创建列)来实现的,从而避免了进行复制的需要。这意味着mixin列将在末尾。可能比黑客更好的解决方案
_creation_order
…