如何在django rest框架中定义列表字段? [英] How can I define a list field in django rest framework?

查看:80
本文介绍了如何在django rest框架中定义列表字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我说一堂课

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
    """

我不太确定从这里到哪里.如何确定博客帖子序列化程序定义为

I am not too sure where to go from here. How can I make sure that a blog post serializer defined as

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

会给我一个类似于

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

推荐答案

为基于非ORM的对象处理数组的一种方法是重写to_nativefrom_native方法.就您而言:

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

如果您有一个基于ORM的对象,则希望查看具有many = True属性的SlugRelatedField.

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

从Django Rest Framework 3.0版开始,您还可以使用ListField http://www.django-rest-framework.org/api- guide/fields/#listfield

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

这篇关于如何在django rest框架中定义列表字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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