問題:我需要輸出由發佈的消息數量決定的TOP X貢獻者。Python Collections.DefaultDict Sort + Output Top X自定義類對象
數據:我收到了一條發佈的消息。下面的示例查詢不是數據庫/ SQL問題,只是給出代碼的概述。
tweetsSQL = db.GqlQuery("SELECT * FROM TweetModel ORDER BY date_created DESC")
我的模型:
class TweetModel(db.Model):
# Model Definition
# Tweet Message ID is the Key Name
to_user_id = db.IntegerProperty()
to_user = db.StringProperty(multiline=False)
message = db.StringProperty(multiline=False)
date_created = db.DateTimeProperty(auto_now_add=False)
user = db.ReferenceProperty(UserModel, collection_name = 'tweets')
從上SO例子,我能夠這樣做是爲了找到頂級的X提供者:現在我可以在排序使用
visits = defaultdict(int)
for t in tweetsSQL:
visits[t.user.from_user] += 1
:
c = sorted(visits.iteritems(), key=operator.itemgetter(1), reverse=True)
但唯一的辦法是沒有w檢索原始對象是循環遍歷對象c,找到KeyName,然後在TweetsSQL中查找它以獲取TweetModel對象。
有沒有更好的方法?
***對不起,我應該補充說,COUNT(*)不可因使用谷歌應用程序引擎
[編輯2]
總結,給出消息的列表,我該怎麼辦按用戶的消息計數排序。
在SQL中,這將是:
SELECT * FROM TweetModel GROUP BY用戶的ORDER BY COUNT(*)
但我不能做在SQL和需要在代碼複製此功能。我的出發點是「SELECT * FROM TweetModel」
對不起,我應該補充說,計數(*)不可用,由於使用谷歌應用程序引擎 – TimLeung 2009-04-20 02:15:45