SQLAlchemy查询从'中间

时间:2015-06-25 23:37:01

标签: python sqlalchemy

我有以下型号(预订服务)

from sqlalchemy_utils import ArrowType

class User:
    id = db.Column(db.Integer, primary_key=True)
    name = Column(db.String(80))

class Service:
    desc = Column(db.String(100))
    provider_id = Column(db.Integer, db.ForeignKey('user.id')
    provider = relationship('User', backref='services')

class TimeSlot:
    start = Column(ArrowType)
    owner_id = Column(db.Integer, db.ForeignKey('user.id')
    owner = relationship('User', backref ='timeslots')

我正在尝试从 用户 开始执行加入,

users = (
    db.session.query(User)
        .join(Service)
        .join(TimeSlot)
        .options(contains_eager(User.services, User.timeslots)
                 )
        .filter(Service.desc == 'Fun')
        .filter(TimeSlot.start == arrow.get('2015-06-15T19:00:00+00:00'))
        .all()
    )

# would like to list the results in a 'nested' way.
for u in users:
    print(u)
    for ts in u.timeslots:
       print(' ', ts)
    for svc in u.services:
       print(' ', svc)

但是,我收到以下错误,

  

属性' User.timeslots'不从元素链接   '映射器|服务|服务'

我理解这是因为.join()的顺序和thaat服务和TimeSlot没有连接。

我应该如何获得用户及其时段+服务列表?

由于

2 个答案:

答案 0 :(得分:0)

users = (
db.session.query(User)
    .join(Service)
    .join(TimeSlot)
    .options(contains_eager(User.services), contains_eager(User.timeslots))
    .filter(Service.desc == 'Fun')
    .filter(TimeSlot.start == arrow.get('2015-06-15T19:00:00+00:00'))
    .all()
)

答案 1 :(得分:0)

尝试from_joinpoint

q = session.query(Node).\
    join("children", aliased=True).\
    filter(Node.name='child 1').\
    join("children", aliased=True, from_joinpoint=True).\
    filter(Node.name == 'grandchild 1')

或reset_joinpoint:

http://docs.sqlalchemy.org/en/latest/orm/query.html#sqlalchemy.orm.query.Query.reset_joinpoint