how to limit/offset sqlalchemy orm relation's result?

前端 未结 1 1897
轻奢々
轻奢々 2021-02-14 19:25

in case i have a user Model and article Model, user and article are one-to-many relation. so i can access article like this

user = session.query(User).filter(id=         


        
相关标签:
1条回答
  • 2021-02-14 19:49

    The solution is to use a dynamic relationship as described in the collection configuration techniques section of the SQLAlchemy documentation.

    By specifying the relationship as

    class User(...):
        # ...
        articles = relationship('Articles', order_by='desc(Articles.date)', lazy='dynamic')
    

    you can then write user.articles.limit(10) which will generate and execute a query to fetch the last ten articles by the user. Or you can use the [x:y] syntax if you prefer which will automatically generate a LIMIT clause.

    Performance should be reasonable unless you want to query the past ten articles for 100 or so users (in which instance at least 101 queries will be sent to the server).

    0 讨论(0)
提交回复
热议问题