使用重复的键属性序列化NDB模型

时间:2013-10-17 23:05:20

标签: python json google-app-engine serialization app-engine-ndb

如何序列化我的模型。我可以在不重复键属性时序列化。

模型如下:

class Properties(ndb.Model):
  propertyID = ndb.StringProperty(required=True)
  propertyParentKey = ndb.KeyProperty()
  propertyItems = ndb.KeyProperty(repeated=True)

我想做点什么

#get all in list
 fetched = model.Properties.query().fetch()

#to a list of dicts
 toSend = [p.to_dict() for p in fetched]

 #Serialize 
  json.dumps(stuff=toSend)

是否有可能以某种方式序列化模型?我该如何处理关键属性列表?

1 个答案:

答案 0 :(得分:2)

为什么不建立自己的json友好字典方法?这样的事情可能就足够了:

def custom_to_dict(self):
    return {
      'propertyId': self.propertyID,
      'propertyParentKey': self.propertyParentKey.urlsafe(),
      'propertyItems': [key.urlsafe() for key in self.propertyItems]
    }

https://developers.google.com/appengine/docs/python/ndb/keyclass#Key_urlsafe

相关问题