【问题标题】:Get only projected properties of an entity仅获取实体的投影属性
【发布时间】:2017-04-18 09:53:39
【问题描述】:

如何在实体的_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...

【问题讨论】:

  • 我知道查询qprojection 属性,只是不明白如何检查属性是否属于投影:q.projection 返回(Demo('first_prop'),)if q_proj and prop in q_proj 只是不工作...

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


【解决方案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 相同的结果。

【讨论】:

    猜你喜欢
    • 2015-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多