Search code examples
pythondjangodjango-modelsdjango-rest-frameworkdrf-queryset

Serializing Array Field to String


I have an array field in my model i need to serialize and return the first 10 tags from the query getting error while serialising the data.

referred - DRF serialize ArrayField as string

serializers.py

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)

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

    class Meta:
        model = Mymodel
        fields = ('id', 'tags')

models.py

class Mymodel(models.Model):
       tags = ArrayField(models.CharField(max_length=64, blank=True),default=list, blank=True)

views.py

class TagsSearchAPIView(APIView):
"""
Used on dropdown menus to dynamically fetch Tags data
"""

    def get(self, request):
        queryset = Mymodel.objects.all()
        tags = queryset.order_by('tags')[:10]
        serialized_tags = TagsSearchSerializer(tags, many=True, context={'request': 
        request})
        results = serialized_tags.data

        return Response({'results': results})

error

 to_representation() takes 1 positional argument but 2 were given

Solution

  • No need to pass self keyword into super().to_representation(obj). Try this one

    def to_representation(self, obj):
        obj = super().to_representation(obj)
        # convert list to string
        return ",".join([str(element) for element in obj])