crimsonpython24
crimsonpython24

Reputation: 2383

Django DjangoRestFramework Appending Item to ListField

I faced this problem while appending a CharField item to ListField: the result list is split into individual characters instead of one string. The files:

# serializers.py

class TodoSerializer(serializers.ModelSerializer):
    key = serializers.IntegerField(source='id')
    levels = serializers.ListField(source='level')    # (a)

    class Meta:
        model = Todo
        fields = ['key', 'title', 'desc', 'level', 'levels', 'created']

(a):

# models.py
level = models.CharField(_('level'), max_length=20)

What I want the ListField to behave is, say the level is normal, I want the ListField to come out as ["normal"]. However, it came out as individual characters, as shown in this image: enter image description here

In one sentence, I want to append level into levels but the format is not satisfactory.

Can anyone please help? Thanks in advance.

Upvotes: 0

Views: 187

Answers (1)

cabesuon
cabesuon

Reputation: 5270

One way to achieve this could be using a custom field. Something like this,

class LevelsField(serializers.Field):

    def to_representation(self, value):
        return [value.level]

    def to_internal_value(self, data):
        # here you need to implement your transform logic
        return ','.join(data)

Then you use it like this,

levels = LevelsField(source='*')

DRF Docs - Serializers - Custom Fields

Upvotes: 2

Related Questions