Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django rest framework serialize ArrayField as string

I have a field in my Model class with an 'ArrayField' and I want it to serialize back and forth as a string of values separated by comma.

models.py

from django.contrib.postgres.fields import ArrayField

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

I followed this solution - 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)

In Serializer:

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

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

But getting bellow error -

TypeError: to_representation() takes 2 positional arguments but 3 were given

Please help.

like image 681
Sneha Shinde Avatar asked Dec 31 '25 19:12

Sneha Shinde


1 Answers

The error suggests you are passing an additional parameter to the method. I noticed that the super() call is incorrect. You can replace that with:

        obj = super().to_representation(obj)
like image 142
arjunattam Avatar answered Jan 02 '26 09:01

arjunattam