【发布时间】:2017-02-26 06:45:48
【问题描述】:
我创建了以下 ORM:
from sqlalchemy import Column, Integer, String, UniqueConstraint
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class TableA(Base):
__tablename__ = 'table_a'
id = Column(Integer, primary_key=True, nullable=False)
identifier = Column(String(320))
internal_id = Column(Integer)
type = Column(String(32))
time = Column(DateTime(timezone=True))
success = Column(Boolean())
parameters = Column(JSONB())
class TableB(Base):
__tablename__ = 'table_b'
__table_args__ = (UniqueConstraint('generate_action',
'print_action',
name='my_action_key'),)
id = Column(Integer, primary_key=True, autoincrement=True, nullable=False)
generate_action = Column(Integer)
print_action = Column(Integer)
generate_action = Column(Integer)
coupon_code = Column(String(300))
number_of_rebought_items = Column(Integer)
seconds_between_rebuy = Column(Integer)
我试图弄清楚如何使用 sqlalchemy 将以下原始 SQL view 转换为 ORM 语法。
CREATE VIEW my_view AS
SELECT table_b.id as table_b_id,
tb.coupon_code as coupon_code,
tb.number_of_rebought_items as number_of_rebought_items,
ta.id as table_a_action_id,
ta.time as time,
ta.parameters as parameters,
FROM table_b tb
LEFT JOIN table_a ta on
ta.id = tb.generate_action;
找不到任何好的例子来说明如何使用 ORM。
到目前为止,我的解决方案是只运行原始 sql 来创建这个视图。
谁能指出我正确的方向,或者举例说明如何使用 sqlalchemy orm 创建视图?
是否可以用metadata.create_all()创建视图
【问题讨论】:
-
不,该问题和答案侧重于使用 sqlalchemy Table 类,而该问题侧重于使用 declarative_base 设置的数据模型。
-
例如,问题中声明的所有表都可以用一行代码创建:Base.metadata.create_all(engine)。是否有类似的方法将 select 语句声明为将通过 create_all 调用或类似方法实例化的视图?
标签: python postgresql view orm sqlalchemy