ndb to_dict方法不包含对象的关键字 [英] ndb to_dict method does not include object's key

查看:79
本文介绍了ndb to_dict方法不包含对象的关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我利用ndb的to_dict方法将对象的属性转换为python字典。从我所知道的一切来看,这个方法并没有在dict中包含对象的key或parent,如下所示:

https://developers.google.com/appengine/docs/python/ndb/modelclass#Model_to_dict



然而,对于我的情况,我需要在字典中的关键。我的意愿是利用内建方法并将其子类化或类似,而不是创建我自己的to_dict方法。



完成此操作的最佳方法是什么?明显的东西?



供参考:我没有为这个项目利用django,而是直接将python部署到gae。



只要在调用to_dict后将该键添加到字典中,并且是覆盖该方法。



如果您的多个模型不与您的自定义to_dict共享相同的基类,那么我会将其作为混合模式实现。



将to_dict定义为Mixin类的一个方法。你会

  class ModelUtils(object):
def to_dict(self):
result = super ModelUtils,self).to_dict()
result ['key'] = self.key.id()#将键作为字符串获取
返回结果




$ b

然后使用它。

  class MyModel ModelUtils,ndb.Model):
#一些属性等...


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 within the dict as per the documentation:

https://developers.google.com/appengine/docs/python/ndb/modelclass#Model_to_dict

However for my situation I need the key to be in the dict. My preference would be to leverage the builtin method and subclass it or something similar rather than create my own to_dict method.

What is the best way to accomplish this or am I missing something obvious? Thanks in advance.

FYI: I am not leveraging django for this project but instead straight python deployed up to gae.

解决方案

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

这篇关于ndb to_dict方法不包含对象的关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆