appengine python NDB排序顺序无效

时间:2017-08-02 16:31:14

标签: python-2.7 google-app-engine app-engine-ndb webapp2

我尝试在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

1 个答案:

答案 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}}不会影响query1query2

来自远程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)