jbp
jbp

Reputation: 125

How to serialize a list of string using Listfield in DRF

I am trying to store a list of keywords using DRF ListField. I am able to POST the list of keywords which is saved properly in the database. But when I retrieve the list with a GET request, I get a list of characters instead of the expected value.

This is my view:

class profile(APIView):

    renderer_classes = [JSONRenderer]
    serializer_class = ProfileSerializer

    def get(self, request):
        serializer = self.serializer_class(request.user.profile)
        return Response(serializer.data, status=200)

    def post(self, request):
        serializer_data = request.data
        serializer = self.serializer_class(request.user.profile, data=serializer_data, partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        return Response(serializer.data, status=200)

This is my serialiser:

class ProfileSerializer(serializers.ModelSerializer):
    keywords = serializers.ListField(child=serializers.CharField(allow_blank=True))


The POST request looks like this:

    {"keywords":["keyword1", "keyword2", "keyword3"]}

POST works fine but when I try to GET the values I get a list like this:

    "keywords": [
        "[",
        "'",
        "k",
        "e",
        "y",
        "w",
        "o",
        "r",
        "d",
        "1",
        "'",
        ",",
        " ",
        "'",
        "k",
        "e",
        "y",
        "w",
        "o",
        "r",
        "d",
        "2",
        "'",
        ",",
        " ",
        "'",
        "k",
        "e",
        "y",
        "w",
        "o",
        "r",
        "d",
        "3",
        "'",
        "]"
    ]

Upvotes: 3

Views: 1002

Answers (1)

marcustas
marcustas

Reputation: 46

You can do this:

keywords = json.loads(request.data['keywords'])}    
serializer = self.serializer_class(
    request.user.profile, data={'keywords': keywords}, partial=True
)

Then in serializer.validated_data you'll have {"keywords":["keyword1", "keyword2", "keyword3"]}

Maybe it looks not good, but with json.loads() you'll have python list instead of string that you are trying to serialize.

Upvotes: 0

Related Questions