1

SQLAlchemy がどのように機能するかについては、まだ混乱しています。今のところ、次のようなクエリがあります

SELECT cast(a.product_id as bigint) id, cast(count(a.product_id) as bigint) itemsSold, cast(b.product_name as character varying)
    from transaction_details a 
    left join product b
    on a.product_id = b.product_id
    group by a.product_id, b.product_name
    order by itemsSold desc;

これがFlaskでどのように変換されるかはよくわかりません。

4

1 に答える 1

3

SQLAlchemy を初めて使用する場合は、オブジェクト リレーショナル チュートリアルSQL 式言語チュートリアルの両方を読んで、その仕組みに慣れてください。Flask-SQLAlchemy 拡張機能を使用しているため、前述のチュートリアルの例でインポートされた多くの名前は、SQLAlchemyクラスのインスタンス (通常dbは Flask-SQLAlchemy の例で名前が付けられています) を介してアクセスできることに注意してください。SA に変換すると、SQL クエリは次のようになります (未テスト)。

# Assuming that A and B are mapped objects that point to tables a and b from
# your example.
q = db.session.query(
    db.cast(A.product_id, db.BigInteger),
    db.cast(db.count(A.product_id), db.BigInteger).label('itemsSold'),
    db.cast(B.product_name, db.String)
# If relationship between A and B is configured properly, explicit join
# condition usually is not needed.
).outerjoin(B, A.product_id == B.product_id).\
group_by(A.product_id, B.product_name).\
order_by(db.desc('itemsSold'))
于 2013-02-21T10:11:38.763 に答える