json 如何在 django rest 框架中定义列表字段?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17289039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 19:53:25  来源:igfitidea点击:

How can I define a list field in django rest framework?

djangojsonlistfielddjango-rest-framework

提问by user1876508

Let's say I have a class

假设我有一堂课

class Tags(object):

    tags = []

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

and a custom list field

和自定义列表字段

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

would give me a json object similar to

会给我一个类似于

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

采纳答案by sebastibe

One way to deal with arraysfor a non ORM-based object is to override the to_nativeand from_nativemethods. In your case:

处理非基于 ORM 的对象的数组的一种方法是覆盖to_nativefrom_native方法。在你的情况下:

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 SlugRelatedFieldwith the many = Trueattribute.

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



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

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

回答by michel.iamit

There is also the ListField in django rest framework, see http://www.django-rest-framework.org/api-guide/fields/#listfield

django rest 框架中也有 ListField,参见http://www.django-rest-framework.org/api-guide/fields/#listfield

wtih the examples:

与示例:

scores = serializers.ListField(
    child=serializers.IntegerField(min_value=0, max_value=100)
)

and (other notation):

和(其他符号):

class StringListField(serializers.ListField):
    child = serializers.CharField()

this seems simpler (maybe this class is added later than the accepted anwser, but seems good to add this option anyway)

这看起来更简单(也许这个类是在接受的 anwser 之后添加的,但无论如何添加这个选项似乎很好)

By the way, it's added since djang rest framework 3.0: http://www.django-rest-framework.org/topics/3.0-announcement/

顺便说一句,它是从 djang rest framework 3.0 开始添加的:http: //www.django-rest-framework.org/topics/3.0-announcement/

回答by Ali Rasim Kocal

If you are using Postgesql, you can use an ArrayField

如果您使用的是 Postgesql,则可以使用ArrayField