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

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

问题描述

我正在利用 ndb 的 to_dict 方法将对象的属性转换为 python dict.据我所知,根据文档,此方法在字典中不包含对象的键或父项:

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

但是,对于我的情况,我需要将密钥放在 dict 中.我更喜欢利用内置方法并将其子类化或类似的东西,而不是创建我自己的 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.

仅供参考:我没有在这个项目中使用 django,而是直接将 python 部署到 gae.

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

推荐答案

你没有遗漏任何东西 ;-)

You're not missing anything ;-)

调用to_dict后把key添加到字典中,yes覆盖该方法.

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

如果您有多个模型与您的自定义 to_dict 不共享相同的基类,我会将其实现为 mixin.

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_dict 定义为 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

然后使用它.

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

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

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