1

外部キーからコレクションの最小/最大を見つけようとしています。andでできることは知っていますがsession.query、標準の ORM 関係を使用できる方法はありますか?func.minfunc.max

たとえば、ブログで、以下のスキーマが与えられた特定の投稿の最大の「コメント数」を見つけたい場合、次のようなことは可能Post.query.get(0).number_comments.max()ですか?

class Post(base):
  id = Column(Integer, primary_key=True)
  number_comments = relationship("NumberComment")

class NumberComment(base):
  id = Column(Integer, primary_key=True)
  num = Column(Integer, nullable=False)
4

1 に答える 1

1

As in case of using raw SQL, you need to join those tables in your query:

# This class lacks a foreign key in your example.
class NumberComment(base):
    # ...
    post_id = Column(Integer, ForeignKey(Post.id), nullable=False)
    # ...

session.query(func.max(NumberComment.num)).join(Post).\
    filter(Post.id == 1).scalar()

There's no other way to do this, at least not like you wanted. There's a reason why SQLAlchemy is called like that and not ORMSorcery ;-)

My advice would be to think in terms of SQL when trying to come up with a query, this will help you a lot.

于 2013-02-03T20:05:25.023 に答える