Using "aliased" in SQLAlchemy ORM

From the SQLAlchemy ORM Tutorial :

You can manage names using the label () construct for scalar attributes and aliases 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 much more typical and much less readable than simple class-based descriptors:

 >>> for row in session.query(User, User.name).all(): ... print row.User, row.name 

But it must exist for some reason. How to use it? What are some good use cases?

+8
python orm sqlalchemy
source share
1 answer

aliased() or alias() are used whenever you need to use the SELECT ... FROM my_table my_table_alias ... in SQL, mainly when using the same table more than once in a query (joins itself, with additional tables or without them). In some cases, you also need subqueries of aliases.

Here is an example in the documentation: http://www.sqlalchemy.org/docs/orm/query.html?highlight=aliased#sqlalchemy.orm.util.AliasedClass

+17
source share

All Articles