Django rest框架将ArrayField序列化为字符串

时间:2018-01-18 20:54:29

标签: python django serialization django-rest-framework

我的Model类中有一个字段,其中包含一个' ArrayField'我想让它来回串行化为一串由逗号分隔的值。

models.py

from django.contrib.postgres.fields import ArrayField

class Test(models.Model):
    colors = ArrayField(models.CharField(max_length=20), null=True, blank=True

我遵循了这个解决方案 - https://stackoverflow.com/questions/47170009/drf-serialize-arrayfield-as-string#=

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)

在Serializer中:

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

    class Meta:
        model = Test
        fields = ('colors') 

但是得到了吼叫错误 -

TypeError:to_representation()需要2个位置参数,但有3个被赋予

请帮忙。

1 个答案:

答案 0 :(得分:2)

该错误表明您正在向该方法传递其他参数。我注意到super()调用不正确。您可以将其替换为:

        obj = super().to_representation(obj)