I have a Student model. And I want to update some specific fields. But when I go to update one or two fields but the other field value is as it is then which fields are not changing those fields show this error** "This field is required.". **
Here is my model.
class Student(models.Model):
teacher=models.ForeignKey(Teacher, on_delete=models.CASCADE)
name=models.CharField(max_length=20)
level=models.CharField(max_length=20)
And here are my views
class StudentUpdateDelete(APIView):
def patch(self, request, id):
student=Student.objects.filter(pk=id).first()
serializer=StudentSerializer(student, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Above model has 3 fields, but I want to change only the name field using the patch method.
If you want to update specific field with the PATCH
method, set partial=True
when you are initializing the serializer
.
So, for your view it would be:
class StudentUpdateDelete(APIView):
def patch(self, request, id):
student=Student.objects.filter(pk=id).first()
serializer=StudentSerializer(student, data=request.data, partial=True)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)