From the SQLAlchemy ORM Tutorial:
You can control the names using the label() construct for scalar attributes and aliased for class constructs:
>>> from sqlalchemy.orm import aliased >>> user_alias = aliased(User, name='user_alias') >>> for row in session.query(user_alias, user_alias.name.label('name_label')).all(): ... print row.user_alias, row.name_label
This seems to be a lot more typing and a lot less readable than the plain class-instrumented descriptors:
>>> for row in session.query(User, User.name).all(): ... print row.User, row.name
But it must exist for a reason. How should it be used? What are some good use cases?
Aliases allow any table or subquery to be referenced by a unique name. In case of a table, this allows the same table to be named in the FROM clause multiple times. It provides a parent name for the columns represented by the statement, allowing them to be referenced relative to this name.
all() method. The Query object, when asked to return full entities, will deduplicate entries based on primary key, meaning if the same primary key value would appear in the results more than once, only one object of that primary key would be present.
The grouping is done with the group_by() query method, which takes the column to use for the grouping as an argument, same as the GROUP BY counterpart in SQL. The statement ends by calling subquery() , which tells SQLAlchemy that our intention for this query is to use it inside a bigger query instead of on its own.
Python Flask and SQLAlchemy ORM All SELECT statements generated by SQLAlchemy ORM are constructed by Query object. It provides a generative interface, hence successive calls return a new Query object, a copy of the former with additional criteria and options associated with it.
aliased()
or alias()
are used whenever you need to use the SELECT ... FROM my_table my_table_alias ...
construct in SQL, mostly when using the same table more than once in a query (self-joins, with or without extra tables). You also need to alias subqueries in certain cases.
There's an example in the documentation: http://www.sqlalchemy.org/docs/orm/query.html?highlight=aliased#sqlalchemy.orm.util.AliasedClass
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