App Engine中的objects.latest()等价物

Mar*_*tin 4 python django google-app-engine

使用AppEngine获取最新插入对象的最佳方法是什么?我知道在Django中可以使用

MyObject.objects.latest()
Run Code Online (Sandbox Code Playgroud)

在AppEngine中,我希望能够做到这一点

class MyObject(db.Model):
  time = db.DateTimeProperty(auto_now_add=True)

# Return latest entry from MyObject.
MyObject.all().latest()
Run Code Online (Sandbox Code Playgroud)

任何的想法 ?

Wil*_*hen 5

你最好的选择是latest()直接实现一个classmethod MyObject并称之为

latest = MyObject.latest()
Run Code Online (Sandbox Code Playgroud)

其他任何东西都需要monkeypatching内置Query类.

更新

我以为我会看到实现这个功能会有多难看.这是一个mixin类,如果你真的想要打电话,你可以使用它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()
Run Code Online (Sandbox Code Playgroud)