简体   繁体   English

如何根据时间戳对 InstrumentedList 进行排序?

[英]How to sort an InstrumentedList based on timestamp?

Currently I have an InstrumentedList that represents a one-to-many relationship in my pyramid app.目前我有一个InstrumentedList代表我的金字塔应用程序中的一对多关系。 The relationship is constructed in the following way:关系的构建方式如下:

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

I want to iterate over every submission in a list of projects.我想遍历项目列表中的每个提交。 However, I want my submissions to be ordered by timestamp (a datetime object)但是,我希望我的提交按时间戳( datetime对象)排序

Here is how I am iterating over my submissions at the moment:以下是我目前迭代提交的方式:

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

The problem is that the order of my submissions for every project changes whenever the app is reloaded.问题是每当重新加载应用程序时,我为每个项目提交的顺序都会发生变化。 I need the order to be consistent and ordered by timestamp, how do I go about doing that?我需要顺序一致并按时间戳排序,我该怎么做?

You'll need to specify an ordering in your relationship definition, using the order_by parameter :您需要使用order_by参数在关系定义中指定排序:

class Project(Base):
    # ...
    submissions = relationship('Submission',
        backref='Project', order_by='Submission.timestamp')

@martjin answer is completely ok , but if you want to order your table in descending order , then use desc() function: @martjin 回答完全没问题,但是如果您想按降序对表格进行排序,请使用desc()函数:

class Project(Base):
    # ...
    submissions = relationship('Submission',
        backref='Project', order_by='Submission.timestamp.desc()')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM