gpt4 book ai didi

python - 如何覆盖 peewee 中的 create_table() 以创建额外的历史记录?

转载 作者:行者123 更新时间:2023-11-30 22:24:20 29 4
gpt4 key购买 nike

正在关注 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 个字段?欢迎所有提示!

最佳答案

也许是这样的:

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。

关于python - 如何覆盖 peewee 中的 create_table() 以创建额外的历史记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35732634/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com