Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of objects.latest() in App Engine

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

MyObject.objects.latest()

in AppEngine I'd 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 ?

like image 666
Martin Avatar asked Feb 27 '23 05:02

Martin


1 Answers

Your best bet will be to implement a latest() classmethod directly on MyObject and call it like

latest = MyObject.latest()

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

Update

I thought I'd see how ugly it would be to implement this functionality. Here's a mixin class you can use if you really want to be able 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()
like image 160
Will McCutchen Avatar answered Apr 09 '23 03:04

Will McCutchen