2 つのモデル:
class this(DeclarativeBase):
__tablename__ = 'this'
'Columns'
id = Column(Integer, primary_key=True)
'Relations'
that = relation('that', foreign_keys=id, backref='this')
class that(DeclarativeBase):
__tablename__ = 'that'
'Columns'
id = Column(Integer, primary_key=True)
this_id = Column(Integer, ForeignKey('this.id'))
この単純な SQL クエリを実行したい:
SELECT id, (SELECT COUNT(*) FROM that WHERE this_id = this1.id) AS thatcount FROM this AS this1
次のようにして、sqlalchemy で同じ結果を得ることができます。
results = session.query(model.this.id,
func.count(model.that.id).label('thatcount')) \
.join(model.that) \
.group_by(model.this.id)
しかし、結果のSQLは私が望むものではありません:
SELECT
this.id AS this_id,
count(that.id) AS thatcount
FROM this
INNER JOIN that ON this.id = that.this_id
GROUP BY this.id
sqlalchemy のいくつかの基本的なアイデアが欠けています...
1) FROM 句でテーブルに「ラベルを付ける」にはどうすればよいですか? 2) 親クエリの結果を参照するサブクエリを作成するにはどうすればよいですか?
私はsqlalchemyに比較的慣れていないので、これは私が理解していない単純なものであることを願っています...もちろん、生のSQLを実行することはできますが、sqlalchemyに感銘を受け、これが可能であると確信しています.
どんな助けでも大歓迎です!