Houy Narun
Houy Narun

Reputation: 1725

How to get column name from sqlalchemy?

Given my models

class CUSTOMER():
    ID              =   db.Column(db.String(12), primary_key=True)
    PotentialCustomer   =   db.Column(db.String(12))
    FirstNameEn     =   db.Column(db.String(35))
    LastNameEn      =   db.Column(db.String(35))
    FirstNameKh     =   db.Column(db.String(35))
    LastNameKh      =   db.Column(db.String(35))
    Salutation      =   db.Column(db.String(4))
    Gender          =   db.Column(db.String(6))
    DateOfBirth     =   db.Column(db.String(10))
    CountryOfBirth  =   db.Column(db.String(2))
    Nationality     =   db.Column(db.String(2))
    ProvinceOfBirth =   db.Column(db.String(3))

I would like to get a list column name of model CUSTOMER() so that I could loop through that column name?

I tried to surfed around via google but has no clue how I can archive that?

Any idea I can archive that? Thanks

Upvotes: 3

Views: 15050

Answers (1)

Víctor López
Víctor López

Reputation: 817

You are searching for column_descriptions().

When you use column_descriptions(), you would get the metadata about the columns which would be returned in the query.

In your case:

customer_alias = aliased(CUSTOMER, name='customer2')
#If you want a single field (CUSTOMER.ID)
customer_query = con.query(CUSTOMER, CUSTOMER.ID, customer_alias)

Then, you should use this expresion:

customer_query.column_descriptions

The output

[
    {
        'name':'CUSTOMER',
        'type':CUSTOMER,
        'aliased':False,
        'expr':CUSTOMER,
        'entity': CUSTOMER
    },
    {
        'name':'ID',
        'type':String(),
        'aliased':False,
        'expr':CUSTOMER.ID,
        'entity': CUSTOMER
    },
    {
        'name':'customer2',
        'type':CUSTOMER,
        'aliased':True,
        'expr':customer_alias,
        'entity': customer_alias
    }
]

But, in case you want all the keys, you should:

#we just want one field:
query = session.query(CUSTOMER).filter_by(id=1)
#then:
conn.execute(query).keys()

And you will get the column names ['id',PotentialCustomer, FirstNameEN...]

Another options:

CUSTOMER.__table__.columns.keys()
CUSTOMER.metadata.columns.keys()

Upvotes: 6

Related Questions