query = some_model.query.filter_by(a=b) count_q = query.statement.with_only_columns([db.func.count()]).order_by(None) count = query.session.execute(count_q).scalar() return count