数日前、別のユースケースについて同じ質問がありました。それを解決するために、必要な変換を行うために、プロパティ タイプのリストを作成しました。このソリューションは、文書化されていない 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)
しかし、より良い解決策があります。次の 2 行を置き換えます。
__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)