2016-07-21 3 views
1

でソートすることにより、最新のエンティティをpony.ormのは、私はpony.ormにマッピングされ、これらのテーブルがあるとしましょう:は関係

class Category(db.Entity): 
    threads = Set("Thread") 

class Thread(db.Entity): 
    category = Required("Category") 
    posts = Set("Post") 

class Post(db.Entity): 
    thread = Required("Thread") 
    timestamp = Required(datetime) 

今、私は、最新の投稿が順特定のカテゴリのすべてのスレッドを取得したい:

この行で私は最新の投稿のIDを取得しますが、私はオブジェクトが欲しいです。もちろん

query = select((max(p.id), p.thread) for p in Post if p.thread.category.id == SOME_ID) 
    .order_by(lambda post_id, thread: -post_id) 

Iでし[(Post[i], thread) for i, thread in query]または

select(p for p in Post if p.id in [i for i,_ in query])しかし、これは追加のSQL文を作成します。だから私の質問は:どのように特定のカテゴリ内のすべてのスレッドの最新の投稿を、その記事のタイムスタンプでソートして、単一のSQL文で取得することができます。

ORMを使用できない場合はdb.execute(sql)を使用しません。

答えて

1

これを試してみてください:私はpony.ormを好きな理由

select((p, t) for t in Thread for p in t.posts 
       if p.id == max(p2.id for p2 in t.posts) 
     ).order_by(lambda p, t: desc(p.id)) 
+0

うわー、それはだ:それはちょうどPythonの。しかし、私が理解していないのは、なぜ、 'select(category.threadsのt)が' '非エンティティオブジェクトを反復する' '無効なのですか?' 'select(t.postsのpのThread for p)いい?どちらの場合も、私は 'Set'関係を繰り返しています。 – Wombatz

+0

'select(tはcategory.threadsの中でt)'も適切ですが、対応する翻訳ロジックはまだ実装されていません。それは比較的簡単に行うべきですが、他のタスクはもっと緊急でした。我々はすぐにそれを実装することを望む。 –