2013-10-17 36 views
1

如何序列化我的模型。当关键属性不重复时,我可以序列化。序列化具有重复键属性的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) 

是否有可能以某种方式序列化模式?我如何处理keyproperties的列表?

+1

那么你为什么不去做呢?有些类型(属性)需要自定义转换为json,如None值等。 –

回答

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

+0

这就是我最终实现的。谢谢。我想确保我没有忽视更常见的事情。 – user2892511