Let's say I have a class

class Tags(object):

    tags = []

    def __init__(self, tags):
        self.tags = tags

和一个自定义列表字段

class TagsField(serializers.WritableField):
    """
    Returns a list of tags, or serializes a list of tags
    """

我不太确定接下来该怎么办.如何确保博客帖子序列化器定义为

class BlogPostSerializer(serializers.Serializer):
    post = CharField()
    tags = TagsField

会给我一个类似于

{
    "post": "Here is my blog post about python",
    "tags": ["python", "django", "rest"]
}

推荐答案

One way to deal with arrays for a non ORM-based object is to override the to_native and from_native methods. In your case:

class TagsField(serializers.WritableField):

    def from_native(self, data):
        if isinstance(data, list):
            return Tags(data)
        else:
            msg = self.error_messages['invalid']
            raise ValidationError(msg)

    def to_native(self, obj):
        return obj.tags

If you had an ORM-based object you would like to look at the SlugRelatedField with the many = True attribute.


From Django Rest Framework version 3.0 you can also use ListField http://www.django-rest-framework.org/api-guide/fields/#listfield

Json相关问答推荐

从先前的REST调用创建动态JSON主体

使用Jolt将字符串数组转换为JSON对象数组

JSON:将项';S键/名称移动到属性中,并使用JQ将其转换为数组

使用WSO2 JsonTransform Mediator对空值执行JsonExceptionUndeletedOperationException

如何将文件夹组织的.json文件合并为一个JSON文件,文件夹/文件名作为键

无法使用Jolt变换在嵌套的JSON中提取值

当由.sh脚本执行时,AWS查询字符串不会提取任何数据

如何将属性拆分为嵌套的JSON内容?

如何使用jolt将嵌套数据变成线性数据

jq可以在两个JSON对象列表中依次添加对象吗?

用于遮蔽卡的 Jolt 规格

从 json 对象中过滤掉所有出现的给定属性

如何配置spring mvc 3在json响应中不返回null对象?

Android 上的 JSON - 序列化

为什么我不能在 C# 中引用 System.Runtime.Serialization.Json

验证和格式化 JSON 文件

使用 Python 3 读取 JSON 文件

与classic 规范化表相比,postgres JSON 索引是否足够高效?

严重:找不到媒体类型 = 应用程序/json、类型 = 类 com.jersey.jaxb.Todo、通用类型 = 类 com.jersey.jaxb.Todo 的 MessageBodyWriter

play 2 JSON 格式中缺少的属性的默认值