将 SQL 视图与 SQLAlchemy ORM class 一起使用?

Use a SQL view with a SQLAlchemy ORM class?

在我的 Postgres 数据库中,我有一个 table 称为操作。我发现自己一遍又一遍地执行相同的复杂查询,所以我决定创建一个视图(投资组合)。

CREATE TABLE actions(
    id UUID NOT NULL PRIMARY KEY,
    utc_date TIMESTAMP WITHOUT TIME ZONE NOT NULL,
    action_type TEXT NOT NULL,
    coin TEXT NOT NULL,
    action_id BYTEA NOT NULL,
    amount NUMERIC(13, 8) NOT NULL,
    investment NUMERIC(7, 2) NOT NULL DEFAULT 0.00,
    wallet TEXT NOT NULL,
    FOREIGN KEY(coin) REFERENCES coins(coin_token),
    FOREIGN KEY(wallet) REFERENCES wallets(name),
    FOREIGN KEY(action_type) REFERENCES action_type(name)
);
CREATE VIEW portfolio AS
SELECT coin,
    SUM(amount) AS amount,
    SUM(investment) AS investment,
    SUM(investment) / SUM(amount) AS min_price
FROM actions
GROUP BY coin
HAVING SUM(amount) > 0.00
ORDER BY coin;
CREATE VIEW actual_investment AS
SELECT SUM(investment)
FROM actions
WHERE action_type IN ('DEPOSIT', 'WITHDRAW');

在我的 python 代码中,我为使用 sqlalchemy 的操作声明了 class。到目前为止它按预期工作,我可以读取和写入 table。但是我还没有找到一种方法来映射投资组合,比如只读 table。我实施的解决方法是在 Python 中模拟 SQL 查询(我有点不喜欢)。

这可能吗?

注意:我找到了这个帖子,但我在视图中没有主键 Is possible to mapping view with class using mapper in SqlAlchemy?

class Portfolio(Base):
    __table__ = Table(
        "portfolio",
        Base.metadata,
        Column("coin", String, primary_key=True),
        Column("amount", Float(precision=13), nullable=False),
        Column("investment", Float(precision=7), nullable=False),
    )

以上代码产生以下错误:

sqlalchemy.exc.ArgumentError: Mapper mapped class Portfolio->portfolio could not assemble any primary key columns for mapped table 'portfolio'

一如既往,我们将不胜感激 :-)

我找到了适用于我的用例的“解决方案”。因为我知道在我看来“coin”列将包含唯一值,所以我将该列重新定义为主键。我想这对于分组依据的任何列都是如此。

我希望这个解决方案适用于遇到此问题的每个人 post :-)