Home > Net >  Django .save() doesn't update on PUT request
Django .save() doesn't update on PUT request

Time:10-30

I am trying to update a foreign-field with a PUT request on a resource. My serializer.data and the http response is correct after callig .is_valid, but the object doesn't get updated.

View

def put(self, request, user_pk):
    try:
        userById = getUserById(user_pk)
    except ChatUser.DoesNotExist:
        raise Http404
    serializer = ChatUserInputSerializer(userById, data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=status.HTTP_200_OK)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Serializer

class IdentificationInputSerializer(serializers.ModelSerializer):
    class Meta:
        model = Identification
        fields = "__all__"
        read_only_fields = ["id"]


class ChatUserInputSerializer(serializers.ModelSerializer):
    identification = IdentificationInputSerializer()

    class Meta:
        model = ChatUser
        fields = ["id", "userId", "identification"]
        read_only_fields = ["id", "userId"]

    def update(self, instance, validated_data):
        identification = validated_data.pop('identification')
        instance.identification.salutation = identification.get('salutation', instance.identification.salutation)
        instance.identification.firstname = identification.get('firstname', instance.identification.firstname)
        instance.identification.name = identification.get('name', instance.identification.name)
        instance.identification.street = identification.get('street', instance.identification.street)
        instance.identification.plz = identification.get('plz', instance.identification.plz)
        instance.identification.city = identification.get('city', instance.identification.city)
        instance.identification.country = identification.get('country', instance.identification.country)
        instance.save()
        return instance

CodePudding user response:

I pretty sure that django won't save related models when you call .save().
Try instance.identification.save()

  • Related