打印 sqlalchemy 行 [英] Print an sqlalchemy row
问题描述
我想要做的就是打印 sqlalchemy 表行的单行.
All I'd like to do is print a single row of an sqlalchemy table row.
说我有:
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class ATable(Base):
__tablename__ = 'atable'
id = Column(Integer, primary_key=True)
name = Column(String(255), nullable=False)
然后我想输出如下所示的任何内容:
Then I'd like to output anything that looks like this:
id: 1
name: theRowName
最好无需在表列中进行硬编码,即更普遍.
Preferable without having to hard code in the table columns, i.e. more generally.
我试过了:
atable = Atable()
... #add some values etc.
print atable
print str(atable)
print repr(atable)
print atable.__table__.c
也考虑过实现 __str__
和 __repr__
,但它们又缺乏通用性要求.
As well as thought about implementing __str__
and __repr__
, but they again lack the generality request.
关于将表格行覆盖到 JSON 中有很多问题,但这并不是我真正想要的,我更关心视觉输出 - 之后不需要机器可读.
There are many questions on covering a table row into JSON, but that's not really what I want, I care more about the visual output - it doesn't need to be machine readable afterwards.
推荐答案
要明确 - 您想要一个通用方法来打印col: value"而不对列名进行硬编码?我不怎么使用 SQLAlchemy,但是像这样的 __str__
方法应该可以工作:
To be clear - you want a general method to print "col: value" without hardcoding the column names? I do not use SQLAlchemy much, but a __str__
method like this should work:
def __str__(self):
output = ''
for c in self.__table__.columns:
output += '{}: {}\n'.format(c.name, getattr(self, c.name))
return output
然后,您可以将该方法放在一个 mixin 类中,以便在模型的其他地方使用.
You can then put that method in a mixin class to use elsewhere in your models.
这篇关于打印 sqlalchemy 行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!