第一种:在serializer中,继承Serilizer时,用一下方法
注意点一:在进行跟新操作时,一般情况下前端发送过来的应该是put请求,因为put请求对应的映射关系是update,如果想要通过post请求来进行更新操作,得在url中修改映射关系。
[path('modify_info/', views.ModifyInfo.as_view({'post':'update'})) #改了映射关系 ]
如果发送put请求,一定要记得在其后带上id(一般是用户id)
127.0.0.1/user/modify_info/11/ 后面一定要有/
在view.py中
class ModifyInfo(GenericViewSet,UpdateModelMixin): queryset = models.User.objects.all() serializer_class = serializer.CreateUserSerializer def update(self, request, *args, **kwargs): #一定要重写update方法 ser = self.get_serializer(data=request.data) print(request.data) if ser.is_valid(): #去后端进行校验 ser.save() #执行ser.save() 就是去serilizer.py调用create()函数,并且在create函数中执行更新操作 return APIResponse(code=1, msg='修改成功',) else: print(ser.errors) return APIResponse(code=0, msg=ser.errors)
在serializer.py中
class CreateUserSerializer(serializers.Serializer): #也可以使用ModelSerializer # class Meta: # model = models.User # fields = ['nicknames', 'sex', 'birthdays','id','birthdays','region'] nicknames = serializers.CharField(max_length=58) birthdays = serializers.DateField() sex = serializers.CharField(max_length=5) telephone = serializers.CharField(max_length=11) region = serializers.CharField(max_length=58) user = models.User.objects.filter(telephone=telephone) def validate(self, attrs): telephone = attrs.get('telephone') nicknames = attrs.get('nicknames') user = models.User.objects.filter(telephone=telephone).first() if nicknames != user.nicknames: return attrs else: raise ValidationError('该昵称已被使用') def create(self, validated_data): #在view中通过ser.save()调用create函数 user = models.User.objects.filter(telephone=validated_data.get('telephone')).first() user.nicknames = validated_data.get('nicknames') user.sex = validated_data.get('sex') user.birthdays = validated_data.get('birthdays') print(validated_data) user.region = validated_data.get('region') user.save() return user #一定要返回对象
第二种,在seriliazer中继承ModelSerializer时用下面方法(写的代码少)
在View.py中
class ModifyInfo(GenericViewSet,UpdateModelMixin):
queryset = models.User.objects.all()
serializer_class = serializer.CreateUserSerializer
#重写UpdateModelMixin中的update
def update(self, request, *args, **kwargs):
print(request.data)
user=models.User.objects.filter(telephone=request.data['telephone']).first()
ser = self.get_serializer(instance=user,data=request.data) #在进行序列化的时候,需要传对象。
print(ser,111)
if ser.is_valid():
ser.save()
return APIResponse(code=1, msg='修改成功',)
else:
print(ser.errors)
return APIResponse(code=0, msg=ser.errors)
在seriliazer中.py中就不需要在写create方法
class CreateUserSerializer(serializers.ModelSerializer): telephone = serializers.CharField(write_only=True) #可以不用去校验返回前端,所以要重写, class Meta: model = models.User fields = ['nicknames', 'sex', 'birthdays','region','telephone'] def validate(self, attrs): telephone = attrs.get('telephone') nicknames = attrs.get('nicknames') print(attrs) user = models.User.objects.filter(telephone=telephone).first() if nicknames != user.nicknames: return attrs else: raise ValidationError('该昵称已被使用')