3

目前InstrumentedList,我的金字塔应用程序中有一个代表一对多关系的关系。关系是通过以下方式构建的:

Class project:
 submissions = relationship('Submission', backref='project')

我想遍历项目列表中的每个提交。但是,我希望我的提交按时间戳(一个datetime对象)排序

以下是我目前对提交的内容进行迭代的方式:

for project in projects:
    for submission in project.submissions:
        # Do some stuff with each submission here

问题是每当重新加载应用程序时,我为每个项目提交的顺序都会发生变化。我需要顺序一致并按时间戳排序,我该怎么做?

4

2 回答 2

12

You'll need to specify an ordering in your relationship definition, using the order_by parameter:

class Project(Base):
    # ...
    submissions = relationship('Submission',
        backref='Project', order_by='Submission.timestamp')
于 2012-07-17T08:46:13.987 回答
1

@martjin 答案完全可以,但是如果您想按降序排列表格,请使用desc()函数:

class Project(Base):
    # ...
    submissions = relationship('Submission',
        backref='Project', order_by='Submission.timestamp.desc()')
于 2021-07-17T01:48:58.940 回答