Peewee 模型,dicts()

Peewee Model, dicts()

我正在调试现有代码。我试图找出在 MyDbBackend.storewarning 语句中明显错误地访问 peewee Model.dicts 的意图,以及我如何纠正它。 我想警告消息应该向无法保存的模型添加更详细的输出。但是,.dicts属性只存在于orm.BaseQueryclass中。

输出消息目前不是很有帮助。鉴于 i.save 失败,我想提供改进的警告消息。 “改进”是指提供一些有关未能保存的记录的元信息。

那么,我如何从 model 中获取 BaseQuery,然后 .dicts 会输出什么?该信息在警告消息的上下文中是否有用?

import peewee as orm


database = orm.Proxy()


class ModelBase(orm.Model):
    class Meta:
        database = database


class MyModel(ModelBase):
    dtfield             = orm.DateTimeField(null=True)
    intfield            = orm.IntegerField(null=True)
    floatfield          = orm.FloatField(null=True)


class MyDbBackend:
    def __init__(self, database):
        self.db = database
        self.records = []  # Holds objects derived from ModelBase

    [...]

    def store(self):
        with self.db.atomic():
            for i in self.records:
                try:
                    i.save()
                except Exception as e:
                    logger.warning("could not save record: {}".format(i.dicts()))
                    raise e

        self.clear()

->

logger.warning("could not save record: {}".format(i.dicts()))
AttributeError: 'MyModel' object has no attribute 'dicts'

我猜原来的代码是为了利用 playhouse.shortcuts.model_to_dict。 这是我唯一的想法,为什么原始代码使用 i.dict()。 可能有些误会。

import peewee as orm
from playhouse.shortcuts import model_to_dict

[...]

logger.warning(f"Model dict: {model_to_dict(i, recurse = True, max_depth = 2)}")
[...]