Reputation: 1441
I need to set some fields (that don't come over as JSON in the request. How do I do so with the Django REST framework.
serializer = GoalSerializer(data=request.DATA)
serializer.status = 'I' ##IS THIS RIGHT????????????????
serializer.journal = id
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)
I do this because status and journal (which is a foreign key field) are required. But always get 400 response. Is this the right way to set those fields?
Upvotes: 1
Views: 391
Reputation: 20838
You want to access:
serializer.object
That is the object that you are going to be saving to the database when when calling:
serializer.save()
So if you are setting extra fields on you Model object before saving it to the database, then you would want to do:
serializer.object.status = "I"
serializer.object.journal = id
Upvotes: 1