如何在Python的SQLAlchemy中排序多对多关系的元素?

2 投票
2 回答
509 浏览
提问于 2025-04-16 21:08

假设有两个模型,它们之间是多对多的关系:

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 列)该怎么办呢?

2 个回答

0

另外,你在 parent = session.query(Parents).first() 里漏掉了一个 s,还有在外键(ForeignKey)里也漏掉了一个 s

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

在关系中,有一个叫做 order_by 的关键字参数可以使用。你可以在 这里 找到更多信息。

撰写回答