python - 等效于 App Engine 中的 objects.latest()

标签 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()

有什么想法吗?

最佳答案

您最好的选择是实现 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/

相关文章:

python - 使用python代码删除目录和子目录中的重复文件

python - Pandas 系列 - 计算列值之间的行数

python - 如何查找包含特定元素的嵌套列表最后一次出现的索引?

python - Matplotlib:3D trisurf 图中的 ax.format_coord() - 返回 (x,y,z) 而不是(方位角,仰角)?

javascript - PUT 请求被多次调用

python - Django 对 3 个相关表的查询优化

google-app-engine - 有没有办法只向 GAE 部署/更新静态内容?

python - windows7中wamp服务器如何配置mod_wsgi

google-app-engine - 批量查询分页?是否可以从数据存储中批量获取并获取游标?

google-app-engine - App Engine 域 CNAME 记录 - "ghs.google.com"或 "ghs.google.com."