How to print all columns in SQLAlchemy ORM

后端 未结 10 1971
再見小時候
再見小時候 2020-12-28 15:18

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;

How

相关标签:
10条回答
  • 2020-12-28 15:36

    Probably the shortest solution (see the recent documentation):

    from sqlalchemy.inspection import inspect
    columns = [column.name for column in inspect(model).c]
    

    The last line might look more readable, if rewrite it in three lines:

    table = inspect(model)
    for column in table.c:
        print column.name
    
    0 讨论(0)
  • 2020-12-28 15:39
    print repr(model.__table__)
    

    Or just the columns:

    print str(list(model.__table__.columns))
    
    0 讨论(0)
  • 2020-12-28 15:40

    Building on Rodney L's answer:

    model = MYMODEL
    columns = [m.key for m in model.__table__.columns]
    
    0 讨论(0)
  • 2020-12-28 15:44

    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!

    0 讨论(0)
提交回复
热议问题