几天前,我对另一个用例有同样的问题。为了解决这个问题,我创建了一个属性类型列表,以进行我需要的转换。该解决方案利用了未记录的 db 函数和 db.Model 类的内部结构。也许有更好的解决方案。
from google.appengine.ext import db
kind = 'Person'
models_module = { 'Person' : 'models'} # module to import the model kind from
model_data_types = {} # create a dict of properties, like DateTimeProperty, IntegerProperty
__import__(models_module[kind], globals(), locals(), [kind], -1)
model_class = db.class_for_kind(kind) # not documented
for key in model_class._properties : # the internals of the model_class object
model_data_types[key] = model_class._properties[key].__class__.__name__
要转换字符串,您可以创建一个具有字符串转换函数的类,例如:
class StringConversions(object)
def IntegerProperty(self, astring):
return int(astring)
def DateTimeProperty(self, astring):
# do the conversion here
return ....
并像这样使用它:
property_name = 'age'
astring = '26'
setattr(Person, property_name, getattr(StringConversions, model_data_types[property_name] )(astring) )
更新:
没有文档: db.class_for_kind(kind)
但是有更好的解决方案。替换这两行:
__import__(models_module[kind], globals(), locals(), [kind], -1)
model_class = db.class_for_kind(kind) # not documented
和 :
module = __import__(models_module[kind], globals(), locals(), [kind], -1)
model_class = getattr(module, kind)