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
classStringArrayField(ListField):
"""
String representation of an array field.
"""defto_representation(self, obj):
obj = super().to_representation(self, obj)
# convert list to stringreturn",".join([str(element) for element in obj])
defto_internal_value(self, data):
data = data.split(",") # convert string to listreturnsuper().to_internal_value(self, data)
Your serializer will become:
classSnippetSerializer(serializers.ModelSerializer):
tags = StringArrayField()
classMeta:
model = Snippetfields= ('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"