0
0

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 1 year has passed since last update.

SqlAlchemy のAsync でデータのカウントをする時

Posted at

## 概要
Sqlalchemy を使っている時に、データのカウントをしたい時、
さらにデータをフィルター(where句)をつけてカウントしたい時はこう書く、というのを忘れないように書いておきます。

where句を使わずに全件カウントする時

from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.engine import Result
from sqlalchemy import select
from sqlalchemy.orm import joinedload
from sqlalchemy.sql.expression import func

result: Result = await db.execute(func.count(log_model.Log.id))
logs = result.scalar()

where句を使う時

user_counts_client = await db.scalar(
    select(func.count())
    .select_from(user_model.User)
    .filter(user_model.User.role == "client")
)

以上です。

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?