Django Rest Framework update field -
i new drf , trying write custom view / serializer can use update 1 field of user object.
i need make logic update "name" of user.
i wrote serializer:
class clientnameserializer(serializers.modelserializer): class meta: model = clientuser fields = ('name',) def update(self, instance, validated_data): instance.name = validated_data.get('name', instance.name) instance.save() return instance
this method never called. tried setting breakpoint there , debug it, never called, if use put, post or patch methods. if add create method being called when use post.
this how view looks like:
class updatename(generics.createapiview): queryset = clientuser.objects.all() serializer_class = clientnameserializer permission_classes = (permissions.isauthenticated,)
does have suggestion? thanks!
my models.py looks this
class clientuser(models.model): owner = models.onetoonefield(user,unique=true,primary_key=true) phone_number = models.charfield(validators=[phone_regex],max_length=20,unique=true) name = models.charfield(max_length=100,blank=true) status = models.integerfield(default=1) member_from = models.datetimefield('member from',auto_now_add=true) is_member = models.booleanfield(default=false)
the definition of methods endpoint can accept done in view, not in serializer.
the update method have under serializer needs moved view you'll have like:
# serializers.py class clientnameserializer(serializers.modelserializer): class meta: model = clientuser # views.py class updatename(generics.updateapiview): queryset = clientuser.objects.all() serializer_class = clientnameserializer permission_classes = (permissions.isauthenticated,) def update(self, request, *args, **kwargs): instance = self.get_object() instance.name = request.data.get("name") instance.save() serializer = self.get_serializer(instance) serializer.is_valid(raise_exception=true) self.perform_update(serializer) return response(serializer.data)
take note you're overriding updatemodelmixin , might need change above code little bit right.
Comments
Post a Comment