def to_dict(self):
return dict((p, unicode(getattr(self, p))) for p in self.properties()
if getattr(self, p) is not None)
你並不需要首先創建一個列表(周圍[]
),您可以只使用一個generator expression的基礎上即時值。
這不是很簡單的,但如果你的模型結構不斷得到一個稍微複雜一些,你可能想看看這個遞歸variant:
# 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
分支。