在保存之前更改POST上的值

时间:2014-03-13 22:12:04

标签: django django-rest-framework

@api_view(['GET', 'POST'])
@csrf_exempt
def index(request):
    if   request.method == 'GET':
    queryset = Test.objects.all()
    return render(request, 'rest_framework/index.html', {'request':request, 'queryset':queryset})
    elif request.method == 'POST':
    post_mutable = request.POST.copy()
        serializer = TestSerializer(data=request.DATA)
    serializer.context = {'request': request}
        if serializer.is_valid():
            serializer.data['test'] = "testing"
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

如何在保存之前更改数据值?我想更改TextField" test"。

1 个答案:

答案 0 :(得分:0)

您可以在TestSerializer类上覆盖.save_object(obj)方法。请参阅docs