The World’s Largest Online Community for Developers

'; python - How to serialize an array to a string in Django Rest Framework? - LavOzs.Com

In a website built with Django I've got a model which has a CharField:

class Person(models.Model):
    name = models.CharField(max_length=255)
    age = models.IntegerField()
    categories = models.CharField(max_length=255)

The CharField can contain a list of strings which are comma separated. For example: ADC,HJD,RTP

Using Django Rest Framework I created a POST endpoint to which people can post new records. That field is posted in json as an array though. So the json looks like this:

    "name": "John",
    "age": 25,
    "categories": ["ADC", "HJD", "RTP"]

I wanted to simply join() the array in the Serializer create() method. But it never reaches that point because it gets filtered out by the validator. I guess the validation is done in the view, but I'm unsure where to start digging.

Does anybody know how I can make the endpoint accept an array and turn it into a comma separated string in a CharField?


These are my ViewSets:

class DevicesViewSet(DatapuntViewSetWritable):
    queryset = Device.objects.all().select_related('owner', 'contact').prefetch_related('types').order_by('id')

    serializer_class = DeviceSerializer
    serializer_detail_class = DeviceSerializer

    http_method_names = ['post', 'list', 'get']

class ContactViewSet(CreateModelMixin, GenericViewSet):
    queryset = Device.objects.none()
    serializer_class = IotContactSerializer
    pagination_class = None

Based on the edited question, here is what you can do. Inherit in your view viewsets.ViewSet and override the create method and write your concatenation logic. Check here

class CreatePersonViewSet (viewsets.ViewSet):
    def create(self, request):
         Do your logic here... to create
How do I check if a string is a number (float)?
How do I parse a string to a float or int?
How do I get a substring of a string in Python?
How do I turn a C# object into a JSON string in .NET?
How to check Django version
How do I lowercase a string in Python?
How to check if the string is empty?
Django REST framework: non-model serializer
Django rest framework, use different serializers in the same ModelViewSet
How to serialize a queryset from an unrelated model as a nested serializer?