【发布时间】:2018-01-18 20:54:29
【问题描述】:
我的模型类中有一个带有“ArrayField”的字段,我希望它以逗号分隔的字符串来回序列化。
models.py
from django.contrib.postgres.fields import ArrayField
class Test(models.Model):
colors = ArrayField(models.CharField(max_length=20), null=True, blank=True
我遵循了这个解决方案 - https://stackoverflow.com/questions/47170009/drf-serialize-arrayfield-as-string#=
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)
在序列化器中:
class SnippetSerializer(serializers.ModelSerializer):
colors = StringArrayField()
class Meta:
model = Test
fields = ('colors')
但出现以下错误 -
TypeError: to_representation() 接受 2 个位置参数,但给出了 3 个
请帮忙。
【问题讨论】:
-
PL.分享一下你用过的自定义Field类的代码。
-
@chatuur 我已经更新了。请检查:)
标签: python django serialization django-rest-framework