使用 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()
有什么想法吗?
最佳答案
您最好的选择是实现 latest()
类方法直接在MyObject
并称它为
latest = MyObject.latest()
任何其他事情都需要对内置 Query
进行猴子修补类。
更新
我想我会看到实现这个功能会有多难看。如果你真的想调用 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()
关于python - 等效于 App Engine 中的 objects.latest(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3730810/