def to_dict(self):
return dict((p, unicode(getattr(self, p))) for p in self.properties()
if getattr(self, p) is not None)
您不需要先创建列表(周围[]
),您可以使用生成器表达式即时构建值。
它不是很简短,但是如果您的模型结构变得更复杂,您可能需要查看这个递归变体:
# Define 'simple' types
SIMPLE_TYPES = (int, long, float, bool, dict, basestring, list)
def to_dict(model):
output = {}
for key, prop in model.properties().iteritems():
value = getattr(model, key)
if isinstance(value, SIMPLE_TYPES) and value is not None:
output[key] = value
elif isinstance(value, datetime.date):
# Convert date/datetime to ms-since-epoch ("new Date()").
ms = time.mktime(value.utctimetuple())
ms += getattr(value, 'microseconds', 0) / 1000
output[key] = int(ms)
elif isinstance(value, db.GeoPt):
output[key] = {'lat': value.lat, 'lon': value.lon}
elif isinstance(value, db.Model):
# Recurse
output[key] = to_dict(value)
else:
raise ValueError('cannot encode ' + repr(prop))
return output
elif
这可以通过添加到分支轻松地用其他非简单类型进行扩展。