关注this SO answer并使用(优秀)Peewee-ORM我正在尝试创建一个版本化数据库,其中记录的历史记录存储在第二个_history表中。因此,当我使用create_table() method创建新的时,我还需要创建一个包含四个额外字段的第二个表。
所以让我说我有下表:
class User(db.Model):
created = DateTimeField(default=datetime.utcnow)
name = TextField()
address = TextField()
创建此表时,我还想创建下表:
class UserHistory(db.Model):
created = DateTimeField() # Note this shouldn't contain a default anymore because the value is taken from the original User table
name = TextField()
address = TextField()
# The following fields are extra
original = ForeignKeyField(User, related_name='versions')
updated = DateTimeField(default=datetime.utcnow)
revision = IntegerField()
action = TextField() # 'INSERT' or 'UPDATE' (I never delete anything)
所以我尝试像这样重写Model类:
class Model(db.Model):
@classmethod
def create_table(cls, fail_silently=False):
db.Model.create_table(cls, fail_silently=fail_silently)
history_table_name = db.Model._meta.db_table + 'history'
# How to create the history table here?
正如你所看到的,我设法用历史表名创建一个变量,但从那里我有点迷失。
有没有人知道如何创建一个像原始表一样的新表,但只是添加了4个字段?欢迎所有提示!
答案 0 :(得分:0)
也许是这样的:
class HistoryModel(Model):
@classmethod
def create_table(cls...):
# Call parent `create_table()`.
Model.create_table(cls, ...)
history_fields = {
'original': ForeignKeyField(cls, related_name='versions'),
'updated': DateTimeField(default=datetime.utcnow),
'revision': IntegerField(),
'action': TextField()}
model_name = cls.__name__ + 'History'
HistoryModel = type(model_name, (cls,), history_fields)
Model.create_table(HistoryModel, ...)
另请注意,您希望对create_indexes()
执行相同的操作。
我建议创建一个属性或其他方法来轻松生成HistoryModel。