python - SQLAlchemy 0.7 MapperEvent 错误

标签 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)

但是运行应用程序后,出现以下错误但未映射

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

出了什么问题?

最佳答案

问题很简单,我在模型中使用了 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的一个bug。 更新:了解更多信息SQLAlchemy abstract

关于python - SQLAlchemy 0.7 MapperEvent 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7990790/

相关文章:

python - 在 python 中使用 ASCII 颜色漂亮地打印 JSON

python - SQLAlchemy 中的一对多+一对关系?

python - sqlalchemy - 强制它永不提交?

python - 使用 REST 在服务器端保存数据

HTMLParser 中的 Python 可重写函数

python - 为什么 BeautifulSoup 将 <html><body><p> 添加到我的结果中?

python - 使用 fast_executemany 写入 MS-Access DB 不起作用

python - 修改函数参数

python - sqlalchemy 中的三元组距离操作

python - 为什么没有检索到具有多对多关系的列名? SQL炼金术