How to print all columns in SQLAlchemy ORM

后端 未结 10 2010
再見小時候
再見小時候 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:29

    Put this together and found it helpful:

    from sqlalchemy import create_engine
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy.orm import sessionmaker
    engine = create_engine('mysql+pymysql://testuser:password@localhost:3306/testdb')
    DeclarativeBase = declarative_base()
    metadata = DeclarativeBase.metadata
    metadata.bind = engine
    
    
    # configure Session class with desired options
    Session = sessionmaker()
    
    # associate it with our custom Session class
    Session.configure(bind=engine)
    
    # work with the session
    session = Session()
    

    And then:

    d = {k: metadata.tables[k].columns.keys() for k in metadata.tables.keys()}
    

    Example output print(d):

    {'orderdetails': ['orderNumber', 'productCode', 'quantityOrdered', 'priceEach', 'orderLineNumber'], 
    'offices': ['addressLine1', 'addressLine2', 'city', 'country', 'officeCode', 'phone', 'postalCode', 'state', 'territory'],
    'orders': ['comments', 'customerNumber', 'orderDate', 'orderNumber', 'requiredDate', 'shippedDate', 'status'],
    'products': ['MSRP', 'buyPrice', 'productCode', 'productDescription', 'productLine', 'productName', 'productScale', 'productVendor', 'quantityInStock'],
    'employees': ['employeeNumber', 'lastName', 'firstName', 'extension', 'email', 'officeCode', 'reportsTo', 'jobTitle'], 
    'customers': ['addressLine1', 'addressLine2', 'city', 'contactFirstName', 'contactLastName', 'country', 'creditLimit', 'customerName', 'customerNumber', 'phone', 'postalCode', 'salesRepEmployeeNumber', 'state'],
    'productlines': ['htmlDescription', 'image', 'productLine', 'textDescription'],
    'payments': ['amount', 'checkNumber', 'customerNumber', 'paymentDate']}
    

    OR and then:

    from sqlalchemy.sql import text
    cmd = "SELECT * FROM information_schema.columns WHERE table_schema = :db ORDER BY table_name,ordinal_position"
    result = session.execute(
                text(cmd),
                {"db": "classicmodels"}
            )
    result.fetchall()
    

提交回复
热议问题