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",
"'",
"]"
]
You can do this:
Then in
serializer.validated_datayou'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.