3

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.

2
  • Pl. share the code of the custom Field class you have used. Commented Jan 19, 2018 at 14:40
  • @chatuur I have updated it.Please check:) Commented Jan 19, 2018 at 15:47

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

2 Comments

This throws an error for me: TypeError: super() takes at least 1 argument (0 given)
You're probably on python2.x. Use super(ClassName, self)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.