序列化 Python 类中的 @property 方法 [英] Serialize the @property methods in a Python class

查看:22
本文介绍了序列化 Python 类中的 @property 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在序列化 Django 模型类时,有没有办法将任何 @property 定义传递给 json 序列化程序?

示例:

class FooBar(object.Model)名称 = 模型.CharField(...)@财产def foo(self):return "我的名字是 %s" %self.name

想要序列化为:

<代码>[{'name' : '测试用户','foo' : '我的名字是测试用户',},]

解决方案

您可以扩展 Django 的序列化程序,而无需/too/太多工作.这是一个自定义序列化程序,它接受一个查询集和一个属性列表(字段与否),并返回 JSON.

from StringIO import StringIO从 django.core.serializers.json 导入序列化器类 MySerializer(Serializer):def 序列化(self, queryset, list_of_attributes, **options):self.options = 选项self.stream = options.get("stream", StringIO())self.start_serialization()对于查询集中的 obj:self.start_object(obj)对于 list_of_attributes 中的字段:self.handle_field(obj, field)self.end_object(obj)self.end_serialization()返回 self.getvalue()def handle_field(self, obj, field):self._current[field] = getattr(obj, field)

用法:

<预><代码>>>>MySerializer().serialize(MyModel.objects.all(), ["field1", "property2", ...])

当然,这可能比编写自己的更简单的 JSON 序列化器要多得多,但可能不会比你自己的 XML 序列化器多(除了更改基类来做到这一点).

Is there a way to have any @property definitions passed through to a json serializer when serializing a Django model class?

example:

class FooBar(object.Model)

    name = models.CharField(...)

    @property
    def foo(self):
        return "My name is %s" %self.name

Want to serialize to:

[{

    'name' : 'Test User',

    'foo' : 'My name is Test User',
},]

解决方案

You can extend Django's serializers without /too/ much work. Here's a custom serializer that takes a queryset and a list of attributes (fields or not), and returns JSON.

from StringIO import StringIO
from django.core.serializers.json import Serializer

class MySerializer(Serializer):
    def serialize(self, queryset, list_of_attributes, **options):
        self.options = options
        self.stream = options.get("stream", StringIO())
        self.start_serialization()
        for obj in queryset:
            self.start_object(obj)
            for field in list_of_attributes:
                self.handle_field(obj, field)
            self.end_object(obj)
        self.end_serialization()
        return self.getvalue()

    def handle_field(self, obj, field):
        self._current[field] = getattr(obj, field)

Usage:

>>> MySerializer().serialize(MyModel.objects.all(), ["field1", "property2", ...])

Of course, this is probably more work than just writing your own simpler JSON serializer, but maybe not more work than your own XML serializer (you'd have to redefine "handle_field" to match the XML case in addition to changing the base class to do that).

这篇关于序列化 Python 类中的 @property 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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