SQLAlchemy定义大型表__repr__的最佳方法

时间:2019-04-16 17:30:24

标签: python sqlalchemy repr

我在SQLAlchemy中有一堆表要定义__repr__

标准约定看起来像这样:

def __repr__(self):
    return "<TableName(id='%s')>" % self.id

这对小桌子来说很好。但是,我有40多个列的表。 是否有更好的方法来构建__repr__,这样我就不必手动键入大字符串了?

我存放所有表的文件称为models.py。我想到的一个解决方案是在_create_repr_string中创建方法models.py,该方法负责自动生成字符串以供__repr__返回。我想知道是否有更标准的方法来创建__repr__

1 个答案:

答案 0 :(得分:1)

在导航日志文件和堆栈跟踪时,对复杂对象具有良好的__repr__很有用,因此,您尝试为此提供一个良好的模式非常好。

我喜欢有一个默认的小助手(在我的情况下,初始化model_class时,BaseModel被设置为flask-sqlalchemy)。

import typing
import sqlalchemy as sa

class BaseModel(Model):

    def __repr__(self) -> str:
        return self._repr(id=self.id)

    def _repr(self, **fields: typing.Dict[str, typing.Any]) -> str:
        '''
        Helper for __repr__
        '''
        field_strings = []
        at_least_one_attached_attribute = False
        for key, field in fields.items():
            try:
                field_strings.append(f'{key}={field!r}')
            except sa.orm.exc.DetachedInstanceError:
                field_strings.append(f'{key}=DetachedInstanceError')
            else:
                at_least_one_attached_attribute = True
        if at_least_one_attached_attribute:
            return f"<{self.__class__.__name__}({','.join(field_strings)})>"
        return f"<{self.__class__.__name__} {id(self)}>"

现在,您可以保持__repr__方法的美观和整洁:

class MyModel(db.Model):

    def __repr__(self):
        # easy to override, and it'll honor __repr__ in foreign relationships
        return self._repr(id=self.id,
                          user=self.user,
                          blah=self.blah)

应产生如下内容:

<MyModel(id=1829,user=<User(id=21, email='foo@bar.com')>,blah='hi')>