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.
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.
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.
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).
¶ 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.
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With