SQLAlchemy eager loading multiple relationships

前端 未结 1 784
一向
一向 2021-02-05 22:17

SQLAlchemy supports eager load for relationship, it is basically a JOIN statement. However, if a model has two or more relationships, it could be a very huge join.

1条回答
  •  再見小時候
    2021-02-05 22:54

    For a one-to-many or many-to-many relationship, it's (usually) better to use subqueryload instead, for performance reasons:

    session.query(Product).join(User.addresses)\
        .options(subqueryload(Product.orders),\
                 subqueryload(Product.tags)).all()
    

    This issues separate SELECT queries for each of orders and tags.

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