使用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()
有什么想法吗?
答案 0 :(得分:5)
您最好的选择是直接在latest()
上实施MyObject
课程方法并将其称为
latest = MyObject.latest()
其他任何内容都需要对内置的Query
类进行monkeypatching。
<强>更新强>
我以为我会看到实现此功能会有多难看。如果您真的希望能够拨打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()
答案 1 :(得分:3)
MyObject.all()返回Query class
的实例按时间排序结果:
MyObject.all().order('-time')
因此,假设至少有一个条目,您可以通过以下方式直接获取最新的MyObject:
MyObject.all().order('-time')[0]
或
MyObject.all().order('-time').fetch(limit=1)[0]