如何在SQLAlchemy中一次加载2个以上的子关系?

时间:2017-03-24 19:28:20

标签: python orm sqlalchemy relationship

我正在尝试将关系加载2级,似乎joinedload()函数将我限制在1个直接关系下一次只有2个。基本上,我想获得promotion's sponsortypecategory

这是错误:

TypeError: joinedload() takes at most 3 arguments (4 given)

代码:

matrix_engagements = matrix_session.query(MatrixEngagement) \
    .filter(MatrixEngagement.id > latest_goldstrike_engagement_id) \
    .options(joinedload('promotion').joinedload('sponsor', 'type',
                                                'category')) \
    .options(joinedload('player'))\
    .options(joinedload('user_coupon').joinedload('coupon').joinedload(
        'reward'))\
    .options(joinedload('kiosk'))\
    .order_by(MatrixEngagement.id.asc()).limit(10).all()

joinedload()功能:

def joinedload(*keys, **kw):
    return _UnboundLoad._from_keys(
        _UnboundLoad.joinedload, keys, False, kw)

似乎应该花费无限量的keys

1 个答案:

答案 0 :(得分:0)

只需添加具有相同父关系的第二行就可以解决问题:

...
.options(joinedload('promotion').joinedload('sponsor', 'type'))\
.options(joinedload('promotion').joinedload('category'))\
...