Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert JSON list of integers to String in Django Rest Framework

I am trying to get list of integers from user and convert those to comma separated string before save model in Django Rest Framework.

My model is like this:

class Message(models.Model):
    name = models.CharField(max_length=100)
    regions = models.TextField(validators=[RegexValidator(regex='^[0-9,]+$')])
    created_at = models.DateTimeField(auto_now_add=True)

and my Serializer:

class MessageSerializer(ModelSerializer):
    regions_list = serializers.ListField(child=serializers.IntegerField())

    class Meta:
        model = Message
        fields = ('id', 'name', 'regions_list', 'created_at')
        read_only_fields = ('created_at')

My input:

{
  "name": "TEST",
  "regions_list": [1, 2, 3, 4]
}

How can I convert regions_list to comma separated string (regions) in db?

Django: 1.10
DRF: 3.5

like image 462
Majid Avatar asked Jan 04 '17 11:01

Majid


Video Answer


1 Answers

I overrode to_representation and to_internal_value methods. It works good for me.

class MessageSerializer(ModelSerializer):
    regions_list = serializers.ListField(child=serializers.IntegerField())

    class Meta:
        model = Message
        fields = ('id', 'name', 'regions_list', 'created_at')
        read_only_fields = ('created_at')

    def to_representation(self, instance: Message):
        instance.regions_list = [int(i) for i in instance.regions.split(',')]
        return super(MessageSerializer, self).to_representation(instance)

    def to_internal_value(self, data):
        ret = super(MessageSerializer, self).to_internal_value(data)
        if ret['regions_list']:
            ret['regions'] = ','.join(str(i) for i in ret['regions_list'])

        return ret
like image 165
Majid Avatar answered Sep 28 '22 05:09

Majid