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

时间:2010-09-16 21:03:56

标签: python django google-app-engine

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

完成
MyObject.objects.latest()
在AppEngine中

我希望能够做到这一点

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

# Return latest entry from MyObject.
MyObject.all().latest()

有什么想法吗?

2 个答案:

答案 0 :(得分:5)

您最好的选择是直接在latest()上实施MyObject课程方法并将其称为

latest = MyObject.latest()

其他任何内容都需要对内置的Query类进行monkeypatching。

<强>更新

我以为我会看到实现此功能会有多难看。如果您真的希望能够拨打MyObject.all().latest()

,可以使用这个mixin课程
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()

答案 1 :(得分:3)

MyObject.all()返回Query class

的实例

按时间排序结果:

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

因此,假设至少有一个条目,您可以通过以下方式直接获取最新的MyObject:

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

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