Лучше всего будет реализовать класс latest()
прямо на MyObject
и назвать его как
latest = MyObject.latest()
Все остальное потребует установки встроенного класса 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()