我一次尝试 2 件新事物,因此感谢您在简化和澄清方面的帮助。
from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy import Column, Float, event
class TimeStampMixin(object):
@declared_attr
def __tablename__(cls):
return cls.__name__.lower()
created = Column(Float)
modified = Column(Float)
def __init__(self, created = None,
modified = None):
self.created = created
self.modified = modified
def create_time(mapper, connection, target):
target.created = time()
#def modified_time(mapper, connection, target):
# target.modified = time()
event.listen(TimeStampMixin, 'before_insert', create_time)
#event.listen(TimeStampMixin, 'before_update', modified_time)
所以我想创建一个可以在任何类中应用的mixin:
class MyClass(TimeStampMixin, Base):
etc, etc, etc
此类继承了在创建时创建时间戳并在更新时创建/修改时间戳的功能。
导入时出现此错误:
raise exc.UnmappedClassError(class_)
sqlalchemy.orm.exc.UnmappedClassError: Class 'db.database.TimeStampMixin' is not mapped
aaaand 我在这一点上被难住了。