我有一个Django Rest Framework API。
我有一个像这样的模型:
class Expression(models.Model):
expression = models.TextField()
result = models.IntegerField()
我的序列化器是这样的:
class ExpressionSerializer(serializers.ModelSerializer):
def __init__(self):
self.operator_mapping = {
"add": " + ",
"minus": " - ",
"divide": " / ",
"multiply": " * "
}
self.data = None
class Meta:
model = Expression
fields = "__all__"
def create(self, validated_data):
expression = self.context.get('expression', None)
result = self.context.get('result', None)
expression_obj = Expression.objects.create(expression=expression, result=result)
return expression_obj
我的视图调用了两个函数valuate_expression和expression_to_string,以修改发送给序列化器的数据:
class ExpressionAPIView(APIView):
queryset = Expression.objects.all()
serializer_class = ExpressionSerializer
def __init__(self):
self.operator_mapping = {
"add": " + ",
"minus": " - ",
"divide": " / ",
"multiply": " * "
}
def get(self, request):
return Response({'data': request.data})
def post(self, request):
root = etree.XML(request.data['expression'])
result = self.evaluate_expression(root)[0]
exp_parsed = self.expression_to_string(root) + f" = {result}"
serializer_data = request.data.get('expression', {})
serializer_context = {
'expression': result,
'result': exp_parsed
}
serializer = self.serializer_class(
data=serializer_data,
context=serializer_context
)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.validated_data, status=status.HTTP_201_CREATED)
不确定我在做什么错,但是我遇到TypeError
__init__() got an unexpected keyword argument 'data'
而且我显然没有向串行器发送正确的数据。
答案 0 :(得分:1)
在您从ExpressionSerializer
继承的ModelSerializer
中,您没有保留ModelSerializer.__init__()
的行为。
您应该像下面的示例一样添加super(ExpressionSerializer, self).__init__(*args, **kwargs)
。
class ExpressionSerializer(serializers.ModelSerializer):
def __init__(self, *args, **kwargs):
self.operator_mapping = {
"add": " + ",
"minus": " - ",
"divide": " / ",
"multiply": " * "
}
super(ExpressionSerializer, self).__init__(*args, **kwargs)
class Meta:
model = Expression
fields = "__all__"
def create(self, validated_data):
expression = self.context.get('expression', None)
result = self.context.get('result', None)
expression_obj = Expression.objects.create(expression=expression, result=result)
return expression_obj
这确保在初始化期间您正在运行ModelSerializer.__init__()
方法。 *args, **kwargs
函数参数在那里接受您可能传递给该函数的任何变量并将它们转发给super方法,因此您可以像常规ModelSerializer
一样使用它并使用您自己的其他参数和代码对其进行扩展。