1

How do I PROGRAMATICALLY find the columns defined in a declarative SQLAlchemy table? I already know how to do it with generic Python reflection, but I was hoping for something more direct. To date, no luck finding it.

Example:

class SomeTable(Base):  # The standard declarative base
  __tablename__ = "hello"
  col1 = Column(Integer)
  col2 = Column(String(10))

I would like to say:

new_row = SomeTable(...) 
...
a lot of code, maybe passing "new_row" to a function
...
either_column_name_list_or_dict = new_row.columns()

and less attractively (but still useful, as classes can be record-kept, too):

either_column_name_list_or_dict = SomeTable.columns()

Frankly, the dict of column names/values or column name/Column objects is better, but I would accept just a list of column names, too (as I can call getattr on them)

To proactively answer the 5000 "Why are you doing that?" replies, I have a very specific need for this (record keeping-based). But that is irrelevant here. Thanks!

Mark Gerolimatos
  • 2,424
  • 1
  • 23
  • 33
  • 1
    Possible duplicate of [get table columns from sqlAlchemy table model](https://stackoverflow.com/questions/24959589/get-table-columns-from-sqlalchemy-table-model), and [method of iterating over sqlalchemy model's defined columns?](https://stackoverflow.com/questions/2537471/method-of-iterating-over-sqlalchemy-models-defined-columns) – Ilja Everilä May 12 '18 at 23:11

1 Answers1

1
[c.name for c in SomeTable.__table__.columns]

gives a list of column names.

Alex Hall
  • 34,833
  • 5
  • 57
  • 89