术语“混淆"的用法.在SQLAlchemy ORM中 [英] Usage of "aliased" in SQLAlchemy ORM

查看:104
本文介绍了术语“混淆"的用法.在SQLAlchemy ORM中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SQLAlchemy ORM教程:

对于标量属性,可以使用label()构造来控制名称;对于类构造,可以使用别名来控制名称:

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?

推荐答案

aliased()alias()在您需要在SQL中使用SELECT ... FROM my_table my_table_alias ...构造时使用,通常是在同一表中多次使用同一张表时查询(自我联接,有或没有额外的表).在某些情况下,您还需要别名查询.

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.

文档中有一个示例: http://www.sqlalchemy.org/docs/orm/query.html?highlight=aliased#sqlalchemy.orm.util.AliasedClass

这篇关于术语“混淆"的用法.在SQLAlchemy ORM中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆