【问题标题】:How to order elements when accesed by many to many relation in pythons SQLAlchemy?python - 在python SQLAlchemy中被多对多关系访问时如何对元素进行排序?
【发布时间】:2011-10-01 14:57:09
【问题描述】:

假设两个模型处于多对多关系:

parent_child = Table('parent_child', metadata,
                         Column('parent_id', Integer, ForeignKey('parent.id')),
                         Column('child_id', Integer, ForeignKey('children.id')))

class Parents(Base):
    __tablename__ = 'parents'
    __table_args__ = {'autoload' : True} # reflecting database

    children = relationship('Child',
                          secondary=parent_child,  # What goes here for sorting?
                          backref='parents')

class Child(Base):
    __tablename__ = 'children'
    __table_args__ = {'autoload' : True} # reflecting database

我知道我能做到

parent = session.query(Parent).first()

获取表中的第一个父元素。正在做

parent.children

返回给定父级的所有子级。 如果我想按生日对它们进行排序(假设模型 Child 具有列 birthdate)怎么办?

【问题讨论】:

    标签: python many-to-many sqlalchemy sql-order-by


    【解决方案1】:

    有一个order_by 关键字参数可用于关系。 here

    【讨论】:

      【解决方案2】:

      您还缺少 parent = session.query(Parents).first() 中的 s 和 ForeignKey 中的 s

      children = relationship('Child', secondary=parent_child, order_by='Child.birthdate', backref='parents')
      

      【讨论】:

        猜你喜欢
        • 2011-08-23
        • 1970-01-01
        • 2014-05-17
        • 1970-01-01
        • 1970-01-01
        • 2014-03-08
        • 2014-08-25
        • 1970-01-01
        • 2021-04-17
        相关资源
        最近更新 更多