Django rest framework update method in API view to changing values in db json
-
21-12-2019 - |
質問
I have an api.py view written as follows in a django rest framework project:
class StudentAcademicProgramList2(APIView):
def get(self, request, format=None):
student_academic_program = Student_academic_program.objects.filter(student=2773951)
serialized_Student_academic_program = StudentAcademicProgramSerializer2(student_academic_program, many=True)
return Response(serialized_Student_academic_program.data)
def update(self, request, format=None):
student_academic_program = Student_academic_program.objects.filter(student=2773951)
serializer = StudentAcademicProgramSerializer2(student_academic_program, many=True)
for x in xrange(0,len(serializer.data)):
serializer.primary_program = False
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status = status.HTTP_201_CREATED)
return Response(serializer.errors, status = status.HTTP_400_BAD_REQUEST)
def post(self, request, format=None):
serializer = StudentAcademicProgramSerializer2(data = request.DATA)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status= status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def delete(self, request, format=None):
student_academic_program = Student_academic_program.objects.filter(student=2773951)
student_academic_program.delete()
return Response(status = status.HTTP_204_NO_CONTENT)
The json it gets is of the following format:
[
{
"id": 3684,
"student": 2773951,
"academic_program": 595,
"credits_completed": 28,
"academic_program_gpa": null,
"primary_program": false
},
{
"id": 3685,
"student": 2773951,
"academic_program": 596,
"credits_completed": 26,
"academic_program_gpa": null,
"primary_program": true
}
]
Both these classes work well whenever i get and post some data in the json api.
How do i write an update()
function in the apiview so that it changes all the primary_program
values in the json to false? The update function i wrote will not work because of the for loop. How can i change this function?
Edit:
I tried @Fabiano 's answer but the serializer was nout updating anything in the db.
解決
def update(self, request, *args, **kwargs):
data = request.DATA
qs = Student_academic_program.objects.filter(student=2773951)
serializer = StudentAcademicProgramSerializer(qs, data=data, many=True)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
...
Or you can allow the user to do a Patch, in this case you just need to add ´partial=True´ on the serializer constructor. If you allow the user to do a Patch, then the user can change only the primary_program field.
serializer = StudentAcademicProgramSerializer(qs, data=data, many=True, partial=True)
You can see more at the docs: http://www.django-rest-framework.org/api-guide/serializers#dealing-with-multiple-objects