2010-01-17 155 views
2

我在飼料模型的10個實體(這是一個App Engine模型)Python列表:如何按時間戳排序? (App Engine的相關)

class Feed(db.Model): 
    sometext = db.StringProperty() 
    timestamp = db.DateTimeProperty(auto_now=True) 

list_of_keys = ["key1","key2","key3".... "key10"] 

,所以我使用db.key叫我的實體()方法:

feeds = db.keys(list_of_keys) 
# this loop below prints the feed 
for feed in feeds: 
    print humanizeTimeDiff(feed.timestamp) 

# humanizeTimeDiff is a function to change the raw timestamp into a human friendly 
# version: eg-> 10 mins ago, 20 seconds ago 

但是現在,如何根據時間戳對Feed進行排序? (我想最新的飼料在頂部和最舊的飼料在底部)

任何排序功能我可以在原始時間戳上使用? (我的粗略計劃是根據原始時間戳進行排序,然後將時間差異人性化)

PS:我不打算使用GQL查詢根據時間戳查詢我的實體,因爲我在表單中得到我的輸入的鍵列表。而使用db.key()是一種更快的方法。

希望我提供了足夠的信息。希望聽到你的想法/解決方案。

回答

10
import operator 

    ... 

for feed in sorted(feeds, key=operator.attrgetter('timestamp'), reverse=True): 
    print humanizeTimeDiff(feed.timestamp) 
相關問題