我想在保存之前编辑django-rest-framwork序列化程序对象。这是我目前的做法-

def upload(request):
    if request.method == 'POST':
        form = ImageForm(request.POST, request.FILES)
        if form.is_valid(): # All validation rules pass
             obj = form.save(commit=False)
             obj.user_id = 15
             obj.save()

我该如何使用django-rest-framework序列化程序对象?
@api_view(['POST','GET'])
def upload_serializers(request):
    if request.method == 'POST':
         serializer = FilesSerializer(data=request.DATA, files=request.FILES)
         if serializer.is_valid():
              serializer.save()

最佳答案

您可以在保存序列化程序之前编辑序列化程序的对象:

if serializer.is_valid():
    serializer.object.user_id = 15 # <----- this line
    serializer.save()

关于python - 保存之前编辑django-rest-framework序列化器对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13563020/

10-11 20:42