2011-12-25 6 views
0

私はこのような単純な1対多の構造を持っている:私は彼のメールでからユーザーをフェッチReferencePropertyを使用すると、日付順に注文する方法を教えてください。

class User(db.Model): 
    userEmail = db.StringProperty() 

class Comment(db.Model): 
    user = db.ReferenceProperty(User, collection_name="comments") 
    comment = db.StringProperty() 
    date = db.DateTimeProperty() 

を:

q = User.all() # prepare User table for querying 
q.filter("userEmail =", "[email protected]") # apply filter, email lookup 
results = q.fetch(1) # execute the query, apply limit 1 
the_user = results[0] # the results is a list of objects, grab the first one 

this_users_comments = the_user.comments # get the user's comments 

は、どのように私は、ユーザーの日付によって、コメント、および制限を注文することができますそれは10のコメントに?

答えて

2

あなたはビルトインsorted機能のkeyキーワード引数を使用すると、キーとして「日付」プロパティを使用します。

import operator 
sorted_comments = sorted(this_users_comments, key=operator.attrgetter("date")) 
# The comments will probably be sorted with earlier comments at the front of the list 
# If you want ten most recent, also add the following line: 
# sorted_comments.reverse() 
ten_comments = sorted_comments[:10] 
+0

が、私は同様のものを使用: '記事=ソート済み(記事、キー=ラムダx:x.modified、逆= True) ' –

0

そのクエリは、ユーザーをフェッチします。あなたはコメントを別のクエリを実行する必要があります。 this_users_comments.order(「日付」)リミット(10) をthis_users_commentsでのコメント:。 ...私はメモリに並べ替える必要がある場合に

関連する問題