ndb to_dict method does not include object's key

前端 未结 2 1254
不思量自难忘°
不思量自难忘° 2021-01-31 11:46

I am leveraging ndb\'s to_dict method to convert an object\'s properties into a python dict. From everything I can tell, this method does not include the object\'s key or parent

2条回答
  •  名媛妹妹
    2021-01-31 12:13

    You're not missing anything ;-)

    Just add the key to the dictionary after you call to_dict, and yes override the method.

    If you have multiple models that don't share the same base class with your custom to_dict, I would implement it as a mixin.

    to define to_dict as a method of a Mixin class. you would

    class ModelUtils(object):
        def to_dict(self):
            result = super(ModelUtils,self).to_dict()
            result['key'] = self.key.id() #get the key as a string
            return result
    

    Then to use it.

    class MyModel(ModelUtils,ndb.Model):
        # some properties etc...
    

提交回复
热议问题