Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/joomla/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
获取最新数据项-谷歌应用程序引擎-Python_Python_Google App Engine_Google Cloud Datastore_Gql - Fatal编程技术网

获取最新数据项-谷歌应用程序引擎-Python

获取最新数据项-谷歌应用程序引擎-Python,python,google-app-engine,google-cloud-datastore,gql,Python,Google App Engine,Google Cloud Datastore,Gql,我需要检索添加到集合中的最新项。我是这样做的: class Box(db.Model): ID = db.IntegerProperty() class Item(db.Model): box = db.ReferenceProperty(Action, collection_name='items') date = db.DateTimeProperty(auto_now_add=True) #get most recent item lastItem = box.

我需要检索添加到集合中的最新项。我是这样做的:

class Box(db.Model):
    ID = db.IntegerProperty()

class Item(db.Model):
    box = db.ReferenceProperty(Action, collection_name='items')
    date = db.DateTimeProperty(auto_now_add=True)

#get most recent item
lastItem = box.items.order('-date')[0]

这是一种昂贵的方式吗?有更好的方法吗?

如果要在框列表上迭代,这是一种非常糟糕的方法。您将为每个框运行额外的查询。你可以很容易地看到发生了什么

如果您正在为每个请求执行其中一项操作,则可能没有问题。但这并不理想。您可能还希望使用:
lastItem=box.items.order('-date').get()
。将只向应用程序返回第一个结果


如果可能,将
lastItem
属性添加到
Box
,或将
Box ID
(您的属性)存储在
项上,速度会明显加快。换句话说,对数据进行非规范化。如果您要获取一个方框列表及其最近的项目,您需要使用这种方法。

完美。我向框中添加了lastItem属性,该属性将在每次向框中添加项目时更新。那好多了。非常感谢。