如何在GAE Python中查询结构化属性中的计算属性

时间:2013-12-27 17:09:24

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

class Name_score(ndb.Model): 
    def get_value_of_name(self, name, date): 
        # concatenate "X" and date before returning 
        return_text = "X"+name+str(date) 
        return return_text 

    date = ndb.DateTimeProperty() 
    name = ndb.StringProperty() 
    # Computed values 
    name_value_computed = ndb.ComputedProperty(lambda e: e.get_value_of_name(e.name, e.date)) 

class Activity_db(ndb.Model): 
    # contains many properties 
    # removed the not relevant ones here 
    name_set = ndb.StructuredProperty(Name_score, repeated=True) 
    hobby = ndb.StringProperty() 

NDB中有很多条目。我想获取特定日期的记录," name_value_computed"匹配查询中提供的数据 查询具有特定" name_value_computed"的所有此类条目和"日期"值(下面的例子),查询是什么。

示例(条件算法):
    ("业余爱好""网球")和((如果在"日期"" 18/01 / 1900"," name_value_computed& #34;是" XJohn18 / 01/1900")或者(如果在"日期"" 22/04 / 1910"," name_value_computed"是" XBran22 / 04/1910"))
以下是正确的:

date_1 = datetime.strptime("18/01/1900", '%d/%m/%Y') 
name_computed_value_1 = "XJohn18/01/1900" 
date_2 = datetime.strptime("22/04/1910", '%d/%m/%Y') 
name_computed_value_2 = "XBran22/04/1910" 
qry_1 = Activity_db.query(ndb.OR(Activity_db.name_set==Name_score(date=date_1, name_value_computed=name_computed_value_1), Activity_db.name_set==Name_score(date=date_2, name_value_computed=name_computed_value_2)), Activity_db.hobby=="tennis") 
record_list = qry_1.fetch() 

我收到以下错误:

File "C:\Program Files (x86)\Google\google_appengine\google\appengine\ext\ndb\model.py", line 2745, in __init__

    self._set_attributes(kwds)

File "C:\Program Files (x86)\Google\google_appengine\google\appengine\ext\ndb\model.py", line 2791, in _set_attributes

    prop._set_value(self, value)

File "C:\Program Files (x86)\Google\google_appengine\google\appengine\ext\ndb\model.py", line 2612, in _set_value

    raise ComputedPropertyError("Cannot assign to a ComputedProperty")

ComputedPropertyError: Cannot assign to a ComputedProperty

我提到了Google Python GAE页面的this section

1 个答案:

答案 0 :(得分:3)

似乎无法直接执行此操作,因为您无法明确指定计算属性的值。

我认为您最好的选择是将计算出的值存储为StringProperty,以便此查询可以正常工作。您可以使用pre-put hook复制计算属性的某些功能。当您将实体放入数据存储区时,您的挂钩可以填充name_value_computed字段。

你的模型看起来像这样:

class Name_score(ndb.Model): 
  def get_value_of_name(self, name, date): 
    # concatenate "X" and date before returning 
    return_text = "X"+name+str(date) 
    return return_text 

  def _pre_put_hook(self):
    self.name_value_computed = self.get_value_of_name(self.name, self.date)

  date = ndb.DateTimeProperty() 
  name = ndb.StringProperty() 
  # Computed values 
  name_value_computed = ndb.StringProperty()

您必须要小心,如果您使用此方法,则需要在访问put()字段之前name_value_computed您的模型,否则它将无法设置。