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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With