代码之家  ›  专栏  ›  技术社区  ›  Martin

相当于对象.最新()应用内引擎

  •  4
  • Martin  · 技术社区  · 14 年前

    使用AppEngine获取最新插入对象的最佳方法是什么?

    MyObject.objects.latest()
    

    看来我希望能做到这一点

    class MyObject(db.Model):
      time = db.DateTimeProperty(auto_now_add=True)
    
    # Return latest entry from MyObject.
    MyObject.all().latest()
    

    你知道吗?

    2 回复  |  直到 14 年前
        1
  •  5
  •   Will McCutchen    14 年前

    你最好的办法是实施 latest() classmethod直接打开 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()
    
        2
  •  3
  •   msbmsb    14 年前

    Query class

    按时间排序结果:

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

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

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