Equivalent to .latest () objects in an Engine application

What would be the best way to get the last inserted object using AppEngine? I know that in Django this can be done using

MyObject.objects.latest() 

in AppEngine I would like to be able to do this

 class MyObject(db.Model): time = db.DateTimeProperty(auto_now_add=True) # Return latest entry from MyObject. MyObject.all().latest() 

Any idea?

+4
source share
2 answers

It would be best to implement the latest() classmethod class directly on MyObject and call it as

 latest = MyObject.latest() 

Anything else would require monkeypatching the built-in Query class.

Update

I thought I would see how ugly it would be to implement this functionality. Here is the mixin class that you can use if you really want to call MyObject.all().latest() :

 class LatestMixin(object): """A mixin for db.Model objects that will add a `latest` method to the `Query` object returned by cls.all(). Requires that the ORDER_FIELD contain the name of the field by which to order the query to determine the latest object.""" # What field do we order by? ORDER_FIELD = None @classmethod def all(cls): # Get the real query q = super(LatestMixin, cls).all() # Define our custom latest method def latest(): if cls.ORDER_FIELD is None: raise ValueError('ORDER_FIELD must be defined') return q.order('-' + cls.ORDER_FIELD).get() # Attach it to the query q.latest = latest return q # How to use it class Foo(LatestMixin, db.Model): ORDER_FIELD = 'timestamp' timestamp = db.DateTimeProperty(auto_now_add=True) latest = Foo.all().latest() 
+5
source

MyObject.all () returns an instance of the request class

Order results by time:

 MyObject.all().order('-time') 

So, if there is at least one entry, you can get the latest MyObject directly:

 MyObject.all().order('-time')[0] 

or

 MyObject.all().order('-time').fetch(limit=1)[0] 
+3
source

All Articles