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?
[EDIT]
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
"""
pass
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.