Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

python - Editing django-rest-framework serializer object before save

I want to edit a django-rest-framwork serializer object before it is saved. This is how I currently do it -

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()

How can I do it with a django-rest-framework serializer object?

@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()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Now edited for REST framework 3

With REST framework 3 the pattern is now:

if serializer.is_valid():
    serializer.save(user_id=15)

Note that the serializers do not now ever expose an unsaved object instance as serializer.object, however you can inspect the raw validated data as serializer.validated_data.

If you're using the generic views and you want to modify the save behavior you can use the perform_create and/or perform_update hooks...

def perform_create(self, serializer):
    serializer.save(user_id=15)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...