DRF将ArrayField序列化为字符串 [英] DRF serialize ArrayField as string

查看:307
本文介绍了DRF将ArrayField序列化为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有ArrayField tags 的模型,我需要它来回序列化为一串用逗号分隔的值。

I have a Model with an ArrayField tags and I need it to serialize back and forth as a string of values separated by comma.

models.py

from django.contrib.postgres.fields import ArrayField

class Snippet(models.Model):
    tags = ArrayField(models.CharField(max_length=255), default=list)

我希望将此字段处理为字符串,例如 tag1,tag2,tag3 可以在模型 save()方法中处理此问题,但DRF抱怨 {tags:[期望项目列表,但类型为 str 。}

I want this field to be handled as a string of tags like tag1,tag2,tag3, I can handle this in the model save() method but DRF is complaining with {tags: ["Expected a list of items but got type "str"."]}.

serializers.py

class SnippetSerializer(serializers.ModelSerializer):

class Meta:
    model = Snippet
        fields = ('tags')

我可以在DRF中做什么以字符串形式管理此字段?我在前端使用React,可以在那里进行处理,但我更喜欢在后端而不是在客户端进行处理。

What can I do in DRF to manage this field as a string ? I am using React in the front-end and I could handle it there but I prefer handling this in the backend rather than the client-side.

推荐答案

您需要创建一个自定义字段来处理所需的格式
postgres ArrayField的其余框架映射字段是ListField,因此您可以将其子类化。

You need to create a custom field that handles the format that you want The rest framework mapping field of postgres ArrayField is a ListField, so you can subclass that.

from rest_framework.fields import ListField

class StringArrayField(ListField):
    """
    String representation of an array field.
    """
    def to_representation(self, obj):
        obj = super().to_representation(self, obj)
        # convert list to string
       return ",".join([str(element) for element in obj])

    def to_internal_value(self, data):
        data = data.split(",")  # convert string to list
        return super().to_internal_value(self, data)

您的序列化器将会变成:

Your serializer will become:

class SnippetSerializer(serializers.ModelSerializer):
    tags = StringArrayField()

    class Meta:
        model = Snippet
        fields = ('tags')

有关在此处编写其余框架自定义字段的更多信息:
http://www.django-rest-framework.org/api-guide/fields/#examples

More info about writing rest framekwork custom fields here: http://www.django-rest-framework.org/api-guide/fields/#examples

这篇关于DRF将ArrayField序列化为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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