Editing django-rest-framework serializer object before save

前端 未结 2 1242
一整个雨季
一整个雨季 2020-12-04 15:22

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 reque         


        
相关标签:
2条回答
  • 2020-12-04 15:52

    You can edit the serializer's object before save the serializer:

    if serializer.is_valid():
        serializer.object.user_id = 15 # <----- this line
        serializer.save()
    
    0 讨论(0)
  • 2020-12-04 16:01

    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)
    
    0 讨论(0)
提交回复
热议问题