Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print all columns in SQLAlchemy ORM

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 

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

like image 374
mrmagooey Avatar asked May 18 '11 02:05

mrmagooey


People also ask

How do I get a list of column names in SQLAlchemy?

To access the column names we can use the method keys() on the result. It returns a list of column names. Since, we queried only three columns, we can view the same columns on the output as well.

What does all () do in SQLAlchemy?

all() method. The Query object, when asked to return full entities, will deduplicate entries based on primary key, meaning if the same primary key value would appear in the results more than once, only one object of that primary key would be present.

What does SQLAlchemy query all return?

Querying (2.0 style) all() and Query. one() will return instances of ORM mapped objects directly in the case that only a single complete entity were requested, the Result object returned by Session.

Should I use SQLAlchemy core or ORM?

In general, if you're trying to programmatically build queries (particularly based on information only available at runtime), you should be using the core. If you're trying to build your application MVC-style and want database-backed objects to be the "model", you should be using the ORM.


1 Answers

This is an old post, but I ran into a problem with the actual database column names not matching the mapped attribute names on the instance. We ended up going with this:

from sqlalchemy import inspect inst = inspect(model) attr_names = [c_attr.key for c_attr in inst.mapper.column_attrs] 

Hope that helps somebody with the same problem!

like image 142
Starktron Avatar answered Sep 18 '22 11:09

Starktron