【发布时间】:2013-12-27 17:09:23
【问题描述】:
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”和“date”值(如下示例)的所有此类条目,查询将是什么。
示例(条件算法):
(“爱好”是“网球”)AND((如果在“日期”“18/01/1900”,“name_value_computed”是“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
【问题讨论】:
-
IIRC,它应该类似于
qry_1 = Activity_db.query(ndb.AND(Activity_db.name_set.date == date_1, Activity_db.name_set.name_value_computed == "nhoJ1"), Activity_db.hobby = "tennis")。实际上,在这里调用ndb.AND是多余的,因为您的所有条件都是“和”在一起的...... -
感谢 mgilson 的回复。您在这里正确指出了不必要的“ndb.AND”(现在已删除)。我的实际查询包含更多条件。但是,我试图在这里提供一个较小的版本(类和查询),只关注它的有问题的部分。我现在试图让我的问题更清楚
-
@mgilson 小心使用 AND。从文档中可以看出,重复字段的两个子属性之间的 AND 在此处的行为不符合预期,因为它可以匹配两个单独的属性。
标签: python google-app-engine google-cloud-datastore app-engine-ndb