ndb to

编程入门 行业动态 更新时间:2024-10-17 11:32:36
本文介绍了ndb to_dict 方法不包含对象的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在利用 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/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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-17 19:37:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/921494.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:ndb

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!