These are the field in my PostSerializer
fields = ('id','user_id','title','desc','comments')
The user_id
and comments
are code generated and title
,desc
were obtained from api calls. I want to pass this as additional values to my request.data
. This is my APIView object
class PostView(APIView):
permission_classes = (IsAuthenticated,)
def post(self,request):
request.data['user_id'] = request.user.id
request.data['comments'] = "machine generated"
post_serializer = PostSerializer(data=request.data)
if post_serializer.is_valid():
post_serializer.save()
print(request.data)
return Response(post_serializer.data)
While my print(request.data)
shows user_id
,comments
fields and their corresponding values. In the saved database though the values for user_id
and comments
are null
.
How do we add and save additional parameters to a serializer object in django rest framework?
Method 1
You can pass additional fields to serializer.save()
as follows:
class PostView(APIView):
permission_classes = (IsAuthenticated,)
def post(self,request):
post_serializer = PostSerializer(data=request.data)
if post_serializer.is_valid():
post_serializer.save (
user_id=request.user_id,
comments="machine generated"
)
return Response(post_serializer.data)
But through this method, you should make blank=True
for user_id
, comments
to make serializer valid.
Method 2
I'm not sure this method works correctly, but i recommend you to not change request.data
.
first copy that and then make changes to new dictionary. as follows:
class PostView(APIView):
permission_classes = (IsAuthenticated,)
def post(self,request):
data = dict(request.data)
data['user_id'] = request.user.id
data['comments'] = "machine generated"
post_serializer = PostSerializer(data=data)
if post_serializer.is_valid():
post_serializer.save()
return Response(post_serializer.data)
Method 3
You can change request.data
with .update()
method without losing data from client side:
class PostView(APIView):
permission_classes = (IsAuthenticated,)
def post(self,request):
request.data.update ( {
'user_id': request.user.id,
'comments': "machine generated text"
} )
post_serializer = PostSerializer(data=request.data)
if post_serializer.is_valid():
post_serializer.save()
print(request.data)
return Response(post_serializer.data)