如何使用ReferenceProperty按日期排序?
问题描述:
我有一个简单的一对多的结构是这样的:如何使用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条评论?
答
你将要使用内置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]
答
该查询获取用户。你需要的意见做另一个查询: this_users_comments.order(“日期”)的限制(10) 在this_users_comments评论: ...
我用类似的东西时,我必须在内存中进行排序:'文章= sorted(articles,key = lambda x:x.modified,reverse = True)' – 2011-12-25 04:05:25