我有一个简单的一对多结构,如下所示:
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 =", "az@example.com") # 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条评论?
答案 0 :(得分:2)
您需要使用内置key
函数的sorted
关键字参数,并使用“date”属性作为键:
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]
答案 1 :(得分:0)
该查询提取用户。您需要对注释执行另一个查询: this_users_comments.order( '日期')。极限(10) 在this_users_comments中发表评论: ...