views:

26

answers:

1

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?

+2  A: 

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.

Robert Kluin
Perfect. I added a lastItem property to Box which will update every time I add an item to Box. That is much better. Thank you.
Eric