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

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

标准约定看起来像这样:

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

这对小桌子来说很好。但是,我有 40 多列的表。 有没有更好的构造方法,__repr__这样我就不会手动输入大量字符串?

我的包含所有表格的文件称为models.py. 一种解决方案我想到了制作方法,_create_repr_stringmodels.py该负责自动生成的字符串进行__repr__返回。我想知道是否有更标准的方式来创建__repr__.


青春有我
浏览 379回答 1
1回答

莫回无

在__repr__导航日志文件和堆栈跟踪时,对复杂对象具有良好功能可能非常有用,因此您尝试为它提出一个好的模式真是太好了。我喜欢有一个默认的小助手(在我的例子中,BaseModel 被设置为model_class初始化flask-sqlalchemy时)。import typingimport sqlalchemy as saclass BaseModel(Model):&nbsp; &nbsp; def __repr__(self) -> str:&nbsp; &nbsp; &nbsp; &nbsp; return self._repr(id=self.id)&nbsp; &nbsp; def _repr(self, **fields: typing.Dict[str, typing.Any]) -> str:&nbsp; &nbsp; &nbsp; &nbsp; '''&nbsp; &nbsp; &nbsp; &nbsp; Helper for __repr__&nbsp; &nbsp; &nbsp; &nbsp; '''&nbsp; &nbsp; &nbsp; &nbsp; field_strings = []&nbsp; &nbsp; &nbsp; &nbsp; at_least_one_attached_attribute = False&nbsp; &nbsp; &nbsp; &nbsp; for key, field in fields.items():&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; field_strings.append(f'{key}={field!r}')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; except sa.orm.exc.DetachedInstanceError:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; field_strings.append(f'{key}=DetachedInstanceError')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; at_least_one_attached_attribute = True&nbsp; &nbsp; &nbsp; &nbsp; if at_least_one_attached_attribute:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return f"<{self.__class__.__name__}({','.join(field_strings)})>"&nbsp; &nbsp; &nbsp; &nbsp; return f"<{self.__class__.__name__} {id(self)}>"现在你可以让你的__repr__方法保持整洁:class MyModel(db.Model):&nbsp; &nbsp; def __repr__(self):&nbsp; &nbsp; &nbsp; &nbsp; # easy to override, and it'll honor __repr__ in foreign relationships&nbsp; &nbsp; &nbsp; &nbsp; return self._repr(id=self.id,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; user=self.user,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; blah=self.blah)应该产生类似的东西:<MyModel(id=1829,user=<User(id=21, email='foo@bar.com')>,blah='hi')>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python