Search code examples
python-3.xormpeewee

Peewee Model, dicts()


I'm debugging existing code. I'm trying to find out the intention of the obviously wrong access to .dicts of a peewee Model in the warning statement in MyDbBackend.store and how I could correct that. I guess that the warning message should add more detailed output to the model which could not be saved. However, the .dicts attribute exists in orm.BaseQuery class, only.

The output message is currently not very helpful. I want to provide an improved warning message given that the i.save fails. With "improved" i mean to provide some meta informations about the record which failed to be saved.

So, how can i obtain the BaseQuery from the model and what would .dicts output, then? Would that information be useful in the context of the warning message?

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'

Solution

  • I guess that the original code was meant to make use of playhouse.shortcuts.model_to_dict. This is the only idea I have why the original code uses i.dict(). Perhaps some misunderstanding.

    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)}")
    [...]