[英]python sqlalchemy select aliased
In sqlalchemy declarative base, I would like to have a class defined from a select. 在sqlalchemy声明式基础中,我想从select中定义一个类。 Maybe I'm confused what is the difference between
sqlalchemy.select()
and session.query()
... If someone could explain me this like I'm a 3 yo (with Python knowledge). 也许我很困惑
sqlalchemy.select()
和session.query()
之间的区别是什么...如果有人可以像我3岁时那样向我解释这一点(具有Python知识)。
I have no trouble with simple joins, like 我可以轻松进行简单的连接,例如
class ViewA(Base):
__select__ = (
sqlalchemy.select([C1.attr1, C2.attr2, ...],
from_obj=C1.__table__.join(C2.__table__)
)
.where(...)
)
__table__ = __select__.alias('view_A')
I'm already using this in the project and it works as I expect it. 我已经在项目中使用了它,并且它可以按我期望的那样工作。 Now, I'm trying to create another view, but with a self join, so I used
orm.aliased()
but it doesn't work, as it says I have 现在,我试图创建另一个视图,但是使用了自我连接,所以我使用了
orm.aliased()
但是它不起作用,因为它说我有
sqlalchemy.exc.ProgrammingError:
(ProgrammingError) (1066, "Not unique table/alias: 'history'", None)
Here is how i'm trying to create my class: 这是我尝试创建班级的方式:
class ViewSummary(Base):
_H1 = orm.aliased(C1, name='c1')
_H2 = orm.aliased(C1, name='c2')
__select__ = (
sqlalchemy.select([_H1.attr1, _H1.attr2, ...],
from_obj=(
_H1.__table__
.outerjoin(_H2.__table__, _H1.id == _H2.id)
.join(AnotherClass, _H1.id == AnotherClass.id)
)
.where(_H2.field is None)
)
__table__ = __select__.alias('view_summary')
Am I mistaken the use of orm.aliased
? 我是否误用了
orm.aliased
?
Thanks for your help, D. 谢谢您的帮助,D。
aliased
is part of the ORM, but select
is not - it's a tool to generate SQL but doesn't map objects to rows. aliased
是ORM的一部分,但select
不是-它是生成SQL的工具,但不会将对象映射到行。 Several of the ORM's constructs won't work with select
and other core constructs. ORM的一些构造不适用于
select
和其他核心构造。
You can try _H1 = C1.__table__.alias()
instead ( aliased
is the ORM equivalent of alias
) 您可以尝试
_H1 = C1.__table__.alias()
代替( aliased
是ORM等价的alias
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.