How to get column names from SQLAlchemy result (declarative syntax)

后端 未结 7 604
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-01 01:26

I am working in a pyramid project and I\'ve the table in SQLAlchemy in declarative syntax

\"\"\"models.py\"\"\"
class Projects(Base):
    __tablename__ = \'proje         


        
7条回答
  •  花落未央
    2021-02-01 01:49

    This link shows how to get all the metadata you could ever need about a table, column and more.

    SQLAlchemy Metadata

    Many of the answers above are based on the info on this page. Suppose we have declared a table.

    employees = Table('employees', metadata,
        Column('employee_id', Integer, primary_key=True),
        Column('employee_name', String(60), nullable=False),
        Column('employee_dept', Integer, ForeignKey("departments.department_id"))
    )
    

    Here are some examples of getting metadata about the table.

    # access the column "EMPLOYEE_ID":
    employees.columns.employee_id
    
    # or just
    employees.c.employee_id
    
    # via string
    employees.c['employee_id']
    
    # iterate through all columns
    for c in employees.c:
        print(c)
    
    # get the table's primary key columns
    for primary_key in employees.primary_key:
        print(primary_key)
    
    # get the table's foreign key objects:
    for fkey in employees.foreign_keys:
        print(fkey)
    
    # access the table's MetaData:
    employees.metadata
    
    # access the table's bound Engine or Connection, if its MetaData is bound:
    employees.bind
    
    # access a column's name, type, nullable, primary key, foreign key
    employees.c.employee_id.name
    employees.c.employee_id.type
    employees.c.employee_id.nullable
    employees.c.employee_id.primary_key
    employees.c.employee_dept.foreign_keys
    
    # get the "key" of a column, which defaults to its name, but can
    # be any user-defined string:
    employees.c.employee_name.key
    
    # access a column's table:
    employees.c.employee_id.table is employees
    
    # get the table related by a foreign key
    list(employees.c.employee_dept.foreign_keys)[0].column.table
    

提交回复
热议问题