SQLAlchemy 0.7 MapperEvent错误

时间:2011-11-03 05:50:49

标签: python sqlalchemy

我有模特

class CreatedMixin(object):

    __abstract__ = True

    @declared_attr
    def created_by(cls):
        return Column(Integer, ForeignKey('user.user_id',
                      onupdate="cascade", ondelete="restrict"))

    @declared_attr
    def updated_by(cls):
        return Column(Integer, ForeignKey('user.user_id',
                      onupdate="cascade", ondelete="restrict"))

    created_at = Column(DateTime, nullable=False, default=dt.now())
    updated_at = Column(DateTime, nullable=False, default=dt.now(),
                        onupdate=dt.now())


class Net(Base, CreatedMixin):
    """Net or subnet."""

    cidr = Column(postgresql.CIDR, index = True)
    description = Column(UnicodeText())

    parent_id = Column(Integer, ForeignKey('net.id'))
    parent = relationship("Net", remote_side="Net.id")

   def __init__(self, cidr=''):
       self.cidr = cidr

   def __repr__(self):
       return "%s" % self.cidr

要自动填充created_by和update_by字段,我使用sqlalchemy.orm.events.MapperEvents(SQLAlchemy 0.7),如下所示:

def created_before_insert_listener(mapper, connection, target):
    # execute a stored procedure upon INSERT,
    # apply the value to the row to be inserted
    #target.calculated_value = connection.scalar(
    #                            "select my_special_function(%d)" 
    #                            % target.special_number)
    target.updated_by = 1

# associate the listener function with CreatedMixin,
# to execute during the "before_insert" hook
event.listen(CreatedMixin, 'before_insert', created_before_insert_listener)

但是在运行app之后,得到了以下错误但未映射

sqlalchemy.orm.exc.UnmappedClassError: Class 'myapp.model.Net' 

怎么了?

1 个答案:

答案 0 :(得分:1)

问题很简单,我在我的模型中使用了Mixin并无意中添加到了属性的基本模型__abstract__ = True

实施例:

from sqlalchemy import *
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session

engine = create_engine('sqlite:///:memory:', echo=True)
Base = declarative_base(bind=engine)
Session = scoped_session(sessionmaker(engine))

class Mix(object):
    __abstract__ = True
    id =  Column(Integer, autoincrement=True, primary_key=True)

class User(Base, Mix):
    __tablename__ = 'users'

    name = Column(String)
    fullname = Column(String)
    password = Column(String)

Base.metadata.create_all()

u = User()
print u

但是在SQLAlchemy 0.6中它运行正常。也许这是一个0.6的错误。 更新:了解更多信息SQLAlchemy abstract