ndb to_dict method does not include object's key

拜拜、爱过 提交于 2019-12-02 17:41:33
Tim Hoffman

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...

Another easy way to achieve that (without having to override to_dict) is to add a ComputedProperty that returns the id, like so:

class MyModel(ndb.Model):

  # this property always returns the value of self.key.id()
  uid = ndb.ComputedProperty(lambda self: self.key.id(), indexed=False)

  # other properties ...

A ComputedProperty will be added to the result of to_dict just like any other property.

There are just two constraints:

  1. Apparently the name of the property can not be key (since that would conflict with the actual key) and id doesn't work either.
  2. This won't work if you don't specify a key or id when you create the object.

Also, the computed value will be written to the data store when you call put(), so it consumes some of your storage space.

An advantage is that this supports the include and exclude arguments of to_dict() out of the box.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!