Getting The Most Recent Data Item - Google App Engine - Python

筅森魡賤 提交于 2020-01-04 05:36:14

问题


I need to retrieve the most recent item added to a collection. Here is how I'm doing it:

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]

Is this an expensive way to do it? Is there a better way?


回答1:


If you are going to iterate over a list of boxes, that is a very bad way to do it. You will run an additional query for every box. You can easily see what is going on with Appstats.

If you are doing one of those per request, it may be ok. But it is not ideal. you might also want to use: lastItem = box.items.order('-date').get(). get will only return the first result to the app.

If possible it would be significantly faster to add a lastItem property to Box, or store the Box ID (your attribute) on Item. In other words, denormalize the data. If you are going to fetch a list of Boxes and their most recent item you need to use this type of approach.



来源:https://stackoverflow.com/questions/3981997/getting-the-most-recent-data-item-google-app-engine-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!