获取最新的数据项 - Google App Engine - Python [英] Getting The Most Recent Data Item - Google App Engine - Python

查看:121
本文介绍了获取最新的数据项 - Google App Engine - Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检索添加到集合中的最新项目。下面是我如何做到这一点:

  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最近的项目
lastItem = box.items.order(' - date')[0]

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

解决方案

如果您打算遍历一列框,这是一种非常糟糕的方式做到这一点。您将为每个框运行一个附加查询。您可以通过 Appstats 轻松查看发生了什么。



如果您正在为每个请求执行其中一项操作,则可能是好的。不过这是不理想的。您可能还想使用: lastItem = box.items.order(' - date')。get()获取只会将第一个结果返回给应用。如果可能的话,将 lastItem 属性添加到 Box code>,或者将 Box ID your attribute )存储在 Item 。换句话说,使数据非规范化。如果您要获取Boxes列表及其最近的项目,则需要使用此类方法。


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?

解决方案

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.

这篇关于获取最新的数据项 - Google App Engine - Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆