如何为从sqlalchemy声明基础扩展的类定义元类

时间:2013-07-03 02:48:09

标签: python dynamic attributes sqlalchemy metaclass

我使用:Python 2.6和sqlalchemy 0.6.1

这就是我想要做的事情:

from sqlalchemy.types import (
    Integer,
    String,
    Boolean
)
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class SampleMeta(type):
    def __new__(cls, name, bases, attrs):
        attrs.update({   'id': Column('Id', Integer, primary_key=True),
                    'name': Column('Name', String),
                    'description': Column('Description', String),
                    'is_active': Column('IsActive', Boolean)
                })
        return super(SampleMeta, cls).__new__(cls, name, bases, attrs)

class Sample(Base):
    __tablename__ = 'Sample'
    __table_args__ = {'useexisting': True}
    __metaclass__ = SampleMeta

    def __init__(self, id, name, description, is_active):
        self.id = id
        self.name = name
        self.description = description
        self.is_active = is_active

    def __repr__(self):
        return "<(%d, '%s', '%s', %r)>" % (self.id, self.name, self.description, self.isactive)

我得到的错误是:

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

现在,如果我使用

执行相同的操作
class Sample(object)

而不是

class Sample(Base)

它的工作非常好。

我需要动态更新类的属性。所以,我将使用动态属性和列名称。我需要上面的代码才能到达那里。

请帮忙

2 个答案:

答案 0 :(得分:8)

要使用元类,在这种情况下,必须从Declaratives DeclaredMeta派生。但是这个用例不需要元类。使用mixins

from sqlalchemy.types import (
    Integer,
    String,
    Boolean
)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column

Base = declarative_base()

class SampleMixin(object):
    id = Column("Id", Integer, primary_key=True)
    name = Column("Name", String)
    description = Column("Description", String)
    is_active = Column("IsActive", Boolean)

class Sample(SampleMixin, Base):
    __tablename__ = 'Sample'
    __table_args__ = {'useexisting': True}

    def __init__(self, id, name, description, is_active):
        self.id = id
        self.name = name
        self.description = description
        self.is_active = is_active

    def __repr__(self):
        return "<(%d, '%s', '%s', %r)>" % (self.id, self.name,
                                self.description, self.isactive)

from sqlalchemy import select
print select([Sample.id, Sample.name])

答案 1 :(得分:-1)

如果zzzeek建议多重继承无法解决您的问题尝试从DeclarativeMeta继承您的MetaClass:

from sqlalchemy.ext.declarative import declarative_base, DeclarativeMeta

Base = declarative_base()

class SampleMeta(DeclarativeMeta):
    #...

class Sample(Base):
    __metaclass__ = SampleMeta
    #...