仅获取实体的预计属性

时间:2016-12-03 16:31:54

标签: google-app-engine google-cloud-datastore app-engine-ndb google-app-engine-python

如何才能在实体的_properties列表中仅在投影查询中指定实体的属性?

我的意思是:

class Demo(ndb.Model):
    first_prop = ndb.StringProperty()
    second_prop = ndb.StringProperty()

Demo( first_prop='First', second_prop='Second' ).put()

q = Demo.query( projection=[first_prop] )
e = q.fetch()
print e[0]._properties.keys()

返回['second_prop', 'first_prop']。我希望len(_properties)1 ...

1 个答案:

答案 0 :(得分:1)

您可以在结果上使用_projection属性(通过在浏览器http://localhost:8080/projection中加载至少两次来调用此处理程序):

import webapp2
from google.appengine.ext import ndb


class Dummy(ndb.Model):
    p1 = ndb.StringProperty()
    p2 = ndb.StringProperty()


class ProjectionHandler(webapp2.RequestHandler):

    def get(self):
        # run this handler at least twice before looking at the console output
        d = Dummy(id='abc')
        d.p1 = 'p1'
        d.p2 = 'p2'
        d.put()
        q = Dummy.query(projection=['p1'])
        r = q.fetch()
        if len(r) > 0:
            print r[0]._properties.keys()  # prints: ['p1', 'p2']
            print r[0]._projection  # prints: ('p1',)

app = webapp2.WSGIApplication([
    ('/projection', ProjectionHandler)
])

此外,

  

q.projection返回(Demo('first_prop'),)

是否有可能代替属性的名称作为字符串,即'first_prop',您传递了Demo.query( projection=[first_prop] )中的实体或其他对象?您应该得到与r[0]._projection相同的结果。