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.