我尝试在model.py中使用这些模型获取最后修改的条目:
class Example(ndb.Model):
....
modified = ndb.DateTimeProperty(auto_now=True)
created = ndb.DateTimeProperty(auto_now_add=True)
查询代码:
for each in ['Example', '...']
model_class = webapp2.import_string('model.%s' % each)
q = model_class.query()
q.order(-model_class.modified)
last_modified_entity = q.get() # does not sort the entities
我也尝试过:
for each in ['Example', '...']
model_class = webapp2.import_string('model.%s' % each)
q = model_class.query()
sort_prop = ndb.GenericProperty('modified')
q.order(-sort_prop)
last_modified_entity = q.get() # does not sort the entities
答案 0 :(得分:2)
在Query对象上调用.order()
不会改变Query对象。它返回一个具有该顺序的新Query对象,但不会更改原始Query对象。来自NDB Queries(强调我的):
而不是在单个表达式中指定整个查询过滤器, 您可能会发现按步骤构建它更方便:例如:
query1 = Account.query() # Retrieve all Account entitites query2 = query1.filter(Account.userid >= 40) # Filter on userid >= 40 query3 = query2.filter(Account.userid < 50) # Filter on userid < 50 too
query3
相当于之前的query
变量 例。 请注意,查询对象是不可变的,所以query2
的构造不会影响query1
和构造query3
的{{1}}不会影响query1
或query2
。
来自远程api shell的示例:
>>>> from models.notification import Notification
>>>> query = Notification.query()
>>>> query
Query(kind='Notification')
>>>>
>>>> # this returns a new ordered query
>>>> query.order(Notification.created_on)
Query(kind='Notification', orders=...)
>>>>
>>>> # but it does not alter the original query
>>>> query
Query(kind='Notification')
>>>>
>>>> # this is how you get the ordered query in a variable
>>>> ordered_query = query.order(Notification.created_on)
>>>> ordered_query
Query(kind='Notification', orders=...)
>>>> query
Query(kind='Notification')
因此,请更改代码以使用此代码:
q = q.order(-sort_prop)