DRF serializer.save()未保存到数据库

时间:2018-11-12 14:13:33

标签: django django-models django-rest-framework django-serializer

我有一个api,它将对资源(MyUser)进行补丁。它可以确认并似乎可以保存对象,但是在查询数据库时,更改尚未保存。

class UserSignupView(generics.UpdateAPIView):
  serializer_class = MyUserSerializer

  def get_object(self, email):
    obj = MyUser.objects.get(email=email)
    self.check_object_permissions(self.request, obj)
    return obj

  def patch(self, request):
    print(request.user)
    user = self.get_object(request.user.email)
    print(user.street)
    serializer = MyUserSerializer(user, data=request.data, partial=True)
    serializer.is_valid(raise_exception=True)
    serializer.save()
    savedUser = MyUser.objects.get(email=request.user.email)
    print(savedUser.street)
    print(serializer.data)
    return Response(serializer.data)


class MyUserSerializer(serializers.ModelSerializer):
  class Meta:
    model = MyUser
    fields = (
        'id', 'first_name', 'last_name', 'email', 'phone_number', 'street', 'locality', 'city',
        'county', 'postcode')

看看我得到的打印语句:
user@example.com

假街123号
MyUser对象

它返回正确的序列化数据,其中包含更改,但数据库没有更改。数据库连接正常,因为我可以查询它并进行其他读/写/等操作。它与UpdateModelMixin几乎相同,除了我必须使用传入的参数覆盖get_object。

1 个答案:

答案 0 :(得分:0)

尝试覆盖更新方法,看看会发生什么:

class MyUserSerializer(serializers.ModelSerializer):
      class Meta:
        model = MyUser
        fields = (
            'id', 'first_name', 'last_name', 'email', 'phone_number', 'street', 'locality', 'city',
            'county', 'postcode')

       def update(self, instance, validated_data):       
        instance.first_name = validated_data.get('first_name',instance.first_name)
        instance.last_name = validated_data.get('last_name',instance.last_name)
        instance.email = validated_data.get('email',instance.email)
        instance.phone_number = validated_data.get('phone_number',instance.phone_number)
        instance.street = validated_data.get('street',instance.street)
        instance.locality = validated_data.get('locality',instance.locality)
        instance.city = validated_data.get('city',instance.city)
        instance.county = validated_data.get('county',instance.county)
        instance.postcode = validated_data.get('postcode',instance.postcode)
        instance.save()
        return instance