【发布时间】:2018-01-10 00:03:19
【问题描述】:
我尝试在 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
【问题讨论】:
-
.get()只返回一个实体。你期待更多吗?它是否返回最新的实体? -
是的,但不是。
-
将
.get()更改为.fetch()看看它会返回什么 -
看看下面我的回答。
q.order(-sort_prop)不会更改q的值。相反,它返回一个带有该排序顺序的新 Query 对象,并且 q 保持未排序。 -
Brendan 的回答是对的:q 是不可变的,它保持未排序,除非您创建它已经排序:
q = model_class.query().order(-sort_prop)
标签: python-2.7 google-app-engine app-engine-ndb webapp2