django-piston:覆盖发射器中的默认序列化

发布于 2024-09-28 16:48:17 字数 344 浏览 0 评论 0原文

我目前正在为 django 项目编写 API,并为此使用 django-piston。但是,我需要自定义某些基本类型的序列化方式。

更准确地说,我的模型是一个特殊的 Model 类的子类,该类继承自 django.db.models.base.ModelBase,但无法序列化为常规 django 模型。因此,我想重写这个特殊 Model 类的所有子类的序列化器。

我不太了解活塞...我查看了代码,并且映射 type->serializer (对于基本类型)似乎是硬编码的。

有人知道是否有标准方法可以覆盖它???

I am currently writing an API for a django project, and using django-piston for this. However, I need to customize the way certain base types are serialized.

More precisely, my models are subclassed from a special Model class, which inherits from django.db.models.base.ModelBase, but cannot be serialized as regular django models ... Therefore, I would like to override the serializer for all subclasses of this special Model class.

I don't know piston well ... I've looked at the code, and the mapping type->serializer (for base types) seems to be hard-coded.

Does anybody know if there is a standard way to override it ???

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

窗影残 2024-10-05 16:48:17

您可以自己进行序列化。处理程序只期望并返回一个 python 字典。但为此,您不能只是将其插入模型中。为您的基本类型创建您自己的资源处理程序,它能够从字典构建您的模型。

class ModelHandler(HandlerBase):
    allowed_methods = ('Get',)

    def read(self, request, id=None):
        if id is not None:
            m = Model.objects.get(id=id)

        ret = {}
        ret['field'] = m.field

        return ret

You can do the serialization yourself. The handlers only expect and return a python dictionary. For this though, you can't just plug it into a model. Create your own resource handler for your base type, which is capable of building your Model from a dict.

class ModelHandler(HandlerBase):
    allowed_methods = ('Get',)

    def read(self, request, id=None):
        if id is not None:
            m = Model.objects.get(id=id)

        ret = {}
        ret['field'] = m.field

        return ret
昵称有卵用 2024-10-05 16:48:17

好吧...我无法让它工作,所以我拿了一些我自己写的代码,让它更干净,它最终成为一个完整的Python序列化框架 SpitEat。我已经开始编写一些文档,但这是一项正在进行的工作。

我已经放弃使用活塞,因为这不是第一次它因在(反)序列化操作上缺乏灵活性而令我失望。

SpitEat 旨在完全可定制(通过从更抽象的角度看待序列化,而不仅仅是“django 对象”),并为 Django 提供序列化器,经过测试,但尚未有很好的文档记录,并且具有功能仍然缺失(这又是一项正在进行的工作)。

Ok ... I couldn't have it working, so I took some code that I had written myself some time ago, made it cleaner, it ended-up in a full Python serialization framework SpitEat. I have begun writing some documentation, but it's a work in progress.

I have given-up using piston, since it is not the first time it disappoints me by its lack of flexibility on (de)serialization operations.

SpitEat aims to be fully customizable, (by seeing serialization from a more abstract point of view than just "django objects") and provides serializers for Django, tested, but not so well documented yet, and with features that are still missing (again it is a work in progress).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文