SQLAlchemy为大型表定义__repr__的最佳方法 [英] SQLAlchemy best way to define __repr__ for large tables

查看:1165
本文介绍了SQLAlchemy为大型表定义__repr__的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a bunch of tables in SQLAlchemy that I want to define __repr__.

标准约定看起来像这样:

The standard convention seems to look like this:

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

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

This is all well and good for small tables. However, I have tables with 40+ columns. Is there a better way of constructing __repr__ such that I am not manually typing out a massive string?

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

My file housing all tables is called models.py. One solution I thought about was making a method _create_repr_string in models.py that takes care of auto-generating the string for __repr__ to return. I am wondering if there is a more standard way to create __repr__.

推荐答案

在导航日志文件和堆栈跟踪时,对复杂对象具有良好的__repr__可能非常有用,因此,您想尝试一个很好的解决方案很好,模式.

Having good __repr__ for complex objects can be incredibly useful when navigating log files and stacktraces, so it's great that you're trying to come up with a good pattern for it.

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

I like to have a little helper with a default (BaseModel gets set as the model_class when initializing flask-sqlalchemy in my case).

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__方法的美观和整洁:

Now you can keep your __repr__ methods nice and neat:

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')>

这篇关于SQLAlchemy为大型表定义__repr__的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆