【问题标题】:Peewee Model, dicts()Peewee 模型,dicts()
【发布时间】:2021-11-22 10:32:51
【问题描述】:

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

输出消息目前不是很有帮助。鉴于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'

【问题讨论】:

    标签: python-3.x orm peewee


    【解决方案1】:

    我猜原始代码是为了使用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)}")
    [...]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-06
      • 2017-10-10
      • 2013-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-28
      • 1970-01-01
      相关资源
      最近更新 更多