使用SQLAlchemy关系order_by的嵌套值

时间:2014-09-10 00:22:39

标签: python sqlalchemy

考虑到这些关系:

A.children = [B...]
B.type = C
C.order = int

如何按.children指定B.type.order关系的顺序?

class A(Base):
    id       = Column(Integer, primary_key=True)
    children = relationship(lambda: B, order_by=lambda: B.type.order)
    #                                           ^^^^^^^^^^^^^^^^^^^^
    #                                           this doesn't work

class B(Base):
    C_id = Column(Integer, ForeignKey(C.id), primary_key=True)
    A_id = Column(Integer, ForeignKey(A.id), primary_key=True)

    type = relationship(lambda: C)

class C(Base):
    id       = Column(Integer, primary_key=True)
    order    = Column(Integer)

给我:

  

AttributeError:与'{1}}关联的'InstrumentedAttribute'对象和'Comparator'对象都没有属性'order'

1 个答案:

答案 0 :(得分:0)

这看起来应该有效:

class A(Base):
    id       = Column(Integer, primary_key=True)
    children = relationship(lambda: B, order_by=lambda: B._order)

class B(Base):
    C_id = Column(Integer, ForeignKey(C.id), primary_key=True)
    A_id = Column(Integer, ForeignKey(A.id), primary_key=True)

    type = relationship(lambda: C)
    _order = column_property(select([C.order]).where(C.id == C_id))

class C(Base):
    id       = Column(Integer, primary_key=True)
    order    = Column(Integer)