Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use alias for column name in SQLAlchemy

Suppose if I have a SQLAlchemy table as follows -

class Employee(Base):
    id = Column(Integer, primary_key=True)
    employee_desgination = Column(String)

I remember going through the docs once and seeing some way of using aliases for long column names and use shorter ones instead. For example, in the above table instead of calling Employee.employee_designation I'd like to use Employee.emp_d or something similar. I wasn't able to find the example again :/ I think you declare an alias() in the table definition, but I am not sure of the syntax.

like image 644
Lyman Zerga Avatar asked Jun 10 '16 22:06

Lyman Zerga


People also ask

How do I use an alias in SQLAlchemy?

In SQLAlchemy, any Table, select() construct, or other selectable object can be turned into an alias using the From Clause. alias() method, which produces an Alias construct. The alias() function in sqlalchemy.

How do I rename a column in SQLAlchemy?

We can select a column with its alias name using the . label() method in SQLAlchemy. Sometimes we got the requirements to show a function result or column name with a different name, you can use the . label() method there.

What does First () do in SQLAlchemy?

Return the first result of this Query or None if the result doesn't contain any row. first() applies a limit of one within the generated SQL, so that only one primary entity row is generated on the server side (note this may consist of multiple result rows if join-loaded collections are present).

Does SQLAlchemy require primary key?

¶ The SQLAlchemy ORM, in order to map to a particular table, needs there to be at least one column denoted as a primary key column; multiple-column, i.e. composite, primary keys are of course entirely feasible as well.


2 Answers

You can specify the actual column name (if different from the attribute name) as the first argument to Column:

emp_d = Column("employee_desgination", String)
like image 181
univerio Avatar answered Oct 09 '22 23:10

univerio


If the table already exist you can reference to the fields directly:

class Humans(Base):
    __table__ = people_table
    id = people_table.c.PeopleID
    name = people_table.c.PeopleName
like image 39
Mandrappa Avatar answered Oct 09 '22 23:10

Mandrappa