【问题标题】:appengine python NDB sort order has no effectappengine python NDB排序顺序没有效果
【发布时间】: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


【解决方案1】:

在 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 不影响 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)

【讨论】:

    猜你喜欢
    • 2013-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-29
    • 1970-01-01
    • 2017-02-14
    • 1970-01-01
    相关资源
    最近更新 更多