0

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
1
  • try removing the super line obj = super().to_representation(self, obj) - that's where the two arguments are coming from.. normally it should be something like super(self).to_representation(obj) but I don't think a super is necessary in that function Commented Oct 13, 2022 at 17:13

1 Answer 1

1

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

Comments

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.