我有一个使用函数填充的序列化器。 因此,我在阵列上堆叠了此特定序列化器的列表。
我如何将每个序列化器数组转换成ListSerializer?
这是我的代码:
serializers.py
class CourseSerializer(serializers.ModelSerializer):
class Meta:
model = models.Course
fields = (
'name',
)
class ErrorSerializer(serializers.Serializer):
error = serializers.CharField(max_length=100)
class Meta:
fields=(
'error',
)
class EqSerializer(serializers.Serializer):
course = CourseSerializer(many=False)
error = ErrorSerializer(many=False)
api.py
...
for c in serializer.validated_data:
course = models.Course.objects.filter(id=1)#simplifying
if len(course)==0:
error="No Courses Found"
elif len(course)>1:
error="Too many courses"
else:
x = serializers.CourseSerializer(course[0])
e = serializers.ErrorSerializer(data={'error':'none'} )
e.is_valid()
equate = serializers.EqSerializer(data={'course':x.data,'error':e.data})
ferr.append(equate) #ferr is my array of EqSerializer
resp = serializers.EqSerializer(data=ferr,many=True)#problem is here
我如何将此ferr
放入serializers.EqSerializer
列表
答案 0 :(得分:0)
万一有人遇到相同的问题,这是解决方案,只需创建一系列字典即可生成ListSerializer,它应该可以工作
for c in serializer.validated_data:
course = models.Course.objects.filter(id=1)#simplifying
if len(course)==0:
error="No Courses Found"
elif len(course)>1:
error="Too many courses"
else:
x = serializers.CourseSerializer(course[0])
e = serializers.ErrorSerializer(data={'error':'none'} )
e.is_valid()
ferr.append({'course':x.data,'error':e.data})
resp = serializers.EqSerializer(data=ferr,many=True)