Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get table columns from sqlAlchemy table model

I have a table where I would like to fetch all the column names however after browsing the interwebs I could not find a way that works. This is what my table looks like:

class myTable(Base):     __tablename__ = 'myTable'      col1 = Column(Integer, primary_key=True)     col2 = Column(Unicode(10))     col3 = Column(Integer)      col4 = Column(Numeric(10, 6))     col5 = Column(Numeric(6,3))     col6 = Column(Numeric(6,3))      child = relationship('tChild',                           backref=backref('children')) 

I would like to be able to print all the column names from a for loop. ex:

"col1", "col2", "col3".... etc 

This is pretty easy with regular sql but I can't seem to figure out how to do it using sqlAlchemy table models

like image 794
john Avatar asked Jul 25 '14 15:07

john


People also ask

How do I get 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 DB Create_all () do?

create_all() function to create the tables that are associated with your models. In this case you only have one model, which means that the function call will only create one table in your database: from app import db, Student. db.

What does SQLAlchemy all () return?

As the documentation says, all() returns the result of the query as a list.

What is column in SQLAlchemy?

function sqlalchemy.orm. column_property(*columns, **kwargs) Provide a column-level property for use with a mapping. Column-based properties can normally be applied to the mapper's properties dictionary using the Column element directly.


2 Answers

You get all of the columns from __table__.columns:

myTable.__table__.columns 

or

myTable.__table__.c 

The columns would be in format myTable.col1 (table name is included). If you want just column names, get the .key for each column:

[column.key for column in myTable.__table__.columns] 
like image 175
alecxe Avatar answered Sep 17 '22 19:09

alecxe


Below is a general as_dict implementation for an sqlalchemy table based on @ChaimG answer. And an additional example of a __repr__ that is implemented using it.

from orm.base import Base   class MyTable(Base):     __tablename__ = 'table_name'      # Columns go here.....      def as_dict(self):         """         Helper function that allows traversing the table's instance columns as key values          :return: (key, value) iterator         """         for key in self.__table__.columns.keys():             value = self.__getattribute__(key)             yield key, value      def __repr__(self):         """         General __repr__ implementation for an sqlalchemy table         """         values = []         for key, value in self.as_dict():             key_value_str = f"{key}={value}"             values.append(key_value_str)          values_str = ", ".join(values)         cls_name = self.__class__.__name__         return f"<{cls_name}({values_str})>" 
like image 35
Roei Bahumi Avatar answered Sep 18 '22 19:09

Roei Bahumi