Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get column names Dynamically with SQLAlchemy

I am querying sqlite db with SQLAlchemy like this:

import db

...

results = session.query(table).all()
        for result in results:
            print result
            print "how to print column name?"

Here is a snippet from db class:

class Device(Base):
    __tablename__ = "devices"
    name = Column(String(250), primary_key=True)
    location = Column(String(250), nullable=False)

    def __init__(self, name, location):
        self.name = name
        self.location = location

Attempting to use ".column_descriptions" on result as per the documentation throws "'list' object has no attribute 'column_descriptions'" error.

What is the proper way of getting column names dynamically along with the values? I want this so I can build a single function to handle json conversion of all queries instead of repeating code all over the place.

like image 425
DominicM Avatar asked Oct 03 '15 20:10

DominicM


People also ask

How to get column names from SQLAlchemy query?

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.

How do I select a column in SQLAlchemy?

SQLAlchemy Core The already created students table is referred which contains 4 columns, namely, first_name, last_name, course, score. But we will be only selecting a specific column. In the example, we have referred to the first_name and last_name columns. Other columns can also be provided in the entities list.

How do I get column names in Python using SQL?

Approach: Connect to a database using the connect() method. Create a cursor object and use that cursor object created to execute queries in order to create a table and insert values into it. Use the description keyword of the cursor object to get the column names.


1 Answers

You can use Device.__table__.columns to get the list of columns in your Device model in your code. These are Column objects and you can get the name by using .name on them while iterating. Then when you query, you can just use getattr or something to get the values that you need.

EDIT:

Example:

col_names = Device.__table__.columns.keys()  # This gets the column names
sample_row = Device.query.first()  # I just query for a random row
required_values = {name: getattr(sample_row, name) for name in col_names}
# This is a dictionary comprehension

You can also use the select syntax, perhaps.

EDIT2:

Here is an article on dictionary comprehension

Okay, so what this dictionary comprehension does is that it gets the keys as the name of column, and the values as the values of corresponding columns from the sample row that I queried for.

You wanted to print a list, so we can do that like this:

Replace the dictionary comprehension line with this.

print([getattr(sample_row, name) for name in col_names])

This will print the values from that row in a list, but you don't get the column names.

But for that you can create a list of tuples.

print([(name, getattr(sample_row, name)) for name in col_names])

But an easier way for you to do this probably would be to use the select syntax instead which is provided by SQLAlchemy.

Docs here: http://docs.sqlalchemy.org/en/rel_0_9/core/tutorial.html#selecting

like image 149
adarsh Avatar answered Sep 28 '22 03:09

adarsh