代码之家  ›  专栏  ›  技术社区  ›  voscausa

appengine python NDB排序顺序没有影响

  •  2
  • voscausa  · 技术社区  · 7 年前

    我尝试在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 回复  |  直到 7 年前
        1
  •  2
  •   Dan Cornilescu    7 年前

    使命感 .order() 在查询对象上,不会更改查询对象。它返回一个具有该顺序的新查询对象,但不改变原始查询对象。从…起 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 以及施工 属于 查询3 不影响 问题1 查询2

    >>>> 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)