开发者

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

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

class B开发者_如何转开发ox(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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜