0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Flask-SQLAlchemyでJoinして特定の値の合計値の降順で並べ替える。

Posted at

メモ的な意味合いを込めて

###Fruitテーブル

id name
1 apple
2 banana
3 orange

###Sellテーブル

id fruit_id count
1 1 1
2 3 3
3 1 2
4 2 8
5 1 2

flask_sqlalchemyにおいて、上記の2つのテーブルから一番出荷された数が多い果物順に並べ替えたい場合は以下のようにする。

# flask_sqlalchemyを使用したdbインスタンスが既に存在するとして
from . import db
from sqlalchemy import desc

fruits = (
    db.session.query(Fruit, db.func.sum(Sell.count).label('count'))
    .filter(Fruit.id == Sell.fruit.id)
    .group_by(Fruit.id)
    .order_by(desc('count'))
    .all()
)

fruitsの中身は以下のようになる。

index Fruit.id Fruit.name count
1 2 banana 8
2 1 apple 5
3 3 orange 3
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?