Search code examples
pythondjangoserializationrequestupdates

how to use django Serializer to update an instance


in Django PUT method, I want to update an instance:

sv= SV.objects.get(pk=pk)
serializer = SVSerializer(sv, data=request.data)
if serializer.is_valid():

Here, in request.data, I just want to pass some of the variable of SV. But as some fields missing, the is_vaild will be false. What I want is, just update the fields in request.data, for the other ones, keep the value in sv. How could I do that?


Solution

  • Perform a partial update by setting partial=True:

    sv= SV.objects.get(pk=pk)
    serializer = SVSerializer(sv, data=request.data, partial=True)
    if serializer.is_valid():
        serializer.save()
    else:
        # Do something else
    

    This allows a PATCH request.

    Edit

    If you want a default field during partial update (as requested in a comment) override the update method:

    SVSerializer(serializers.ModelSerializer): # Instead of exposing the 
        state_flag = serializers.SlugRelatedField(source='sv_state', queryset=SVState.objects.all(), slug_field='flag')
        
        def update(self, instance, validated_data):
            if self.partial and validated_data.get('state_flag') == None:
                validated_data['state_flag'] = 0
            super().update(instance=instance, validated_data=validated_data)