Skip to content Skip to sidebar Skip to footer

DRF Serialize ArrayField As String

I have a Model with an ArrayField tags and I need it to serialize back and forth as a string of values separated by comma. models.py from django.contrib.postgres.fields import Arra

Solution 1:

You need to create a custom field that handles the format that you want The rest framework mapping field of postgres ArrayField is a ListField, so you can subclass that.

from rest_framework.fields import ListField

class StringArrayField(ListField):
    """
    String representation of an array field.
    """
    def to_representation(self, obj):
        obj = super().to_representation(self, obj)
        # convert list to string
       return ",".join([str(element) for element in obj])

    def to_internal_value(self, data):
        data = data.split(",")  # convert string to list
        return super().to_internal_value(self, data)

Your serializer will become:

class SnippetSerializer(serializers.ModelSerializer):
    tags = StringArrayField()

    class Meta:
        model = Snippet
        fields = ('tags')

More info about writing rest framekwork custom fields here: http://www.django-rest-framework.org/api-guide/fields/#examples


Post a Comment for "DRF Serialize ArrayField As String"