所以我是这个 python 和 sqlalchemy 的新手。我需要一些关于继承的帮助,或者可能是一个 mixin(而是继承)。
我有一些伪代码,但我还没有真正取得任何进展:
Base = declarative_base()
class ModelBase(Base):
"""Base model that only defines last_updated"""
__tablename__ = 'doesnotexistandtheclassshouldnotbeinstantiated'
#all tables inheriting from ModelBase will have this column
last_updated = Column(DateTime)
def __init__(self, last_updated):
self.last_updated = last_updated
class User(ModelBase):
"""Defines the user but should also have the last_updated inherited from ModelBase"""
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
def __init__(self, ....):
ModelBase.__init__(last_updated)
我希望从 ModelBase 继承的所有表也都具有 last_updated。我该怎么做?
更新代码:
class BaseUserMixin(object):
"""Base mixin for models using stamped data"""
@declared_attr
def last_updated(cls):
return Column(DateTime)
@declared_attr
def last_updated_by(cls):
return Column(String)
def __init__(self, last_updated, last_updated_by):
self.last_updated = last_updated
self.last_updated_by = last_updated_by
Base = declarative_base(cls=BaseUserMixin)
class User(Base):
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
name = Column(String)
email = Column(String)
fullname = Column(String)
password = Column(String)
enabled = Column(Boolean)
def __init__(self, name, fullname, password, email, last_updated, last_updated_by):
self.name = name
self.fullname = fullname
self.password = password
self.email = email
# goes wrong here
super(User, self).__init__(last_updated, last_updated_by)
def __repr__(self):
return "<User('%', '%', '%', '%', '%', '%')>"\
% (self.name,
self.fullname,
self.password,
self.email,
self.last_updated,
self.last_updated_by
)
错误是:
_declarative_constructor() takes exactly 1 argument (3 given)
可能是什么问题?我认为它正在工作,但是当重新运行调试器时它失败了。