我正在使用谷歌应用引擎/ python。我已经创建了一个自定义数据类型和属性。但我使用它有问题。这是我的定义
from datetime import datetime
class MyDateTime(datetime):
def __str__(self):
return self.strftime("%Y-%m-%d %H:%M")
class MyDateTimeProperty(db.Property):
# specify datatype
data_type = MyDateTime
# For writing to datastore.
def get_value_for_datastore(self, model_instance):
return super(MyDateTimeProperty, self).get_value_for_datastore(model_instance)
# For reading from datastore.
def make_value_from_datastore(self, value):
return super(MyDateTimeProperty, self).validate(value)
class MyClass(db.Model):
date = MyDateTimeProperty()
这就是我使用它的方式:
obj = MyClass(date=MyDateTime(2011,1,1))
obj.put()
我收到以下错误消息:
Traceback (most recent call last):
File "C:\Program Files\Google\google_appengine\google\appengine\ext\admin\__init__.py", line 295, in post
exec(compiled_code, globals())
File "<string>", line 23, in <module>
File "C:\Program Files\Google\google_appengine\google\appengine\ext\db\__init__.py", line 1052, in put
self._populate_internal_entity()
File "C:\Program Files\Google\google_appengine\google\appengine\ext\db\__init__.py", line 1020, in _populate_internal_entity
self._entity = self._populate_entity(_entity_class=_entity_class)
File "C:\Program Files\Google\google_appengine\google\appengine\ext\db\__init__.py", line 1092, in _populate_entity
self._to_entity(entity)
File "C:\Program Files\Google\google_appengine\google\appengine\ext\db\__init__.py", line 1005, in _to_entity
self.__set_property(entity, prop.name, prop.get_value_for_datastore(self))
File "C:\Program Files\Google\google_appengine\google\appengine\ext\db\__init__.py", line 995, in __set_property
entity[name] = datastore_value
File "C:\Program Files\Google\google_appengine\google\appengine\api\datastore.py", line 881, in __setitem__
datastore_types.ValidateProperty(name, value)
File "C:\Program Files\Google\google_appengine\google\appengine\api\datastore_types.py", line 1477, in ValidateProperty
'Unsupported type for property %s: %s' % (name, v.__class__))
BadValueError: Unsupported type for property date: <class '__main__.MyDateTime'>
我已经搜索了一段时间的解决方案但无法解决它。如果有人知道如何解决它,请提前致谢。
谢谢你的回答。我发现主要问题是自定义数据类型无法进入数据存储区,因此我需要使用get_value_for_datastore
和make_value_from_datastore
这是我修改后的属性定义:
class MyDateTimeProperty(db.Property):
# specify datatype
data_type = MyDateTime
# For writing to datastore.
def get_value_for_datastore(self, model_instance):
date = super(MyDateTimeProperty, self).get_value_for_datastore(model_instance)
return datetime(date.year, date.month, date.day, date.hour, date.minute)
# For reading from datastore.
def make_value_from_datastore(self, value):
if value is None:
return None
return MyDateTime(value.year, value.month, value.day, value.hour, value.minute)
关键是,使用get_value_for datastore
将不可存储的MyDateTime对象更改为可存储的日期时间对象,然后使用make_value_from_datastore
反之亦然。
答案 0 :(得分:3)
如果Property
子类的数据类型不是默认验证器所知的已定义数据存储数据类型之一,则需要定义validate()
子类。 this article中有一个验证方法示例。