如何打印 SQLAlchemy ORM 中的所有列 [英] How to print all columns in SQLAlchemy ORM
问题描述
使用 SQLAlchemy,我试图以类似于以下方式打印出每个模型的所有属性:
Using SQLAlchemy, I am trying to print out all of the attributes of each model that I have in a manner similar to:
SELECT * from table;
但是,我想在获得每个模型实例信息后对其进行处理.到目前为止,我能想到的最好的是:
However, I would like to do something with each models instance information as I get it. So far the best that I've been able to come up with is:
for m in session.query(model).all():
print [getattr(m, x.__str__().split('.')[1]) for x in model.__table__.columns]
# additional code
这会给我我正在寻找的东西,但这是一种相当迂回的获取方式.我有点希望有以下属性:
And this will give me what I'm looking for, but it's a fairly roundabout way of getting it. I was kind of hoping for an attribute along the lines of:
m.attributes
# or
m.columns.values
我觉得我错过了一些东西,有一个更好的方法来做到这一点.我这样做是因为我会将所有内容打印到 .CSV 文件,而且我不想指定我感兴趣的列/属性,我想要所有内容(很多列中有很多要打印的模型).
I feel I'm missing something and there is a much better way of doing this. I'm doing this because I'll be printing everything to .CSV files, and I don't want to have to specify the columns/attributes that I'm interested in, I want everything (there's a lot of columns in a lot of models to be printed).
推荐答案
看看 SQLAchemy 的 元数据反射 功能.
Take a look at SQLAchemy's metadata reflection feature.
可以指示 Table 对象从数据库中已经存在的相应数据库模式对象加载有关其自身的信息.这个过程叫做反射.
A Table object can be instructed to load information about itself from the corresponding database schema object already existing within the database. This process is called reflection.
这篇关于如何打印 SQLAlchemy ORM 中的所有列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!