Usage of “aliased” in SQLAlchemy ORM

坚强是说给别人听的谎言 提交于 2020-05-10 07:36:10

问题


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?


回答1:


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




回答2:


As @jd. said,mostly when using the same table more than once in a query. Example:

    dict_code_type, dict_code_status = aliased(DictCode), aliased(DictCode)
    query = Device.query \
      .join(dict_code_type, dict_code_type.codeValue == Device.deviceType) \
      .join(dict_code_status, dict_code_status.codeValue == Device.status) \
      .with_entities(Device.id, Device.deviceName, Device.status,
                   Device.deviceID, Device.deviceUsername, Device.token,
                   dict_code_type.codeLabel.label('deviceTypeLabel'),
                   dict_code_status.codeLabel.label('statusLabel'),  Device.createAt, Device.authType) \
    .filter(and_(dict_code_type.code == 'deviceType', dict_code_status.code == 'status'))


来源:https://stackoverflow.com/questions/5350033/usage-of-aliased-in-sqlalchemy-orm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!