I am saving a model like this
if serializer.is_valid():
message = serializer.save(version_info='55')
and I am passing a parameter called version_info and inside my serializer I have the following code
class MessageSerializer(serilizer.Serializer):
def create(self, validated_data, **kwargs):
message = Message.objects.create(**validated_data)
return message
version_info parameter is inside validated_data dictionary but I want to pass this version_info to save method of my Message model which I have customize it to do some extra work while a message being saved but it gives this error: TypeError: Message() got an unexpected keyword argument 'version_info' how can I pass the version_info parameter to save method of my model?
CodePudding user response:
Using the context
You can add it to the context when you construct the serializer, so:
serializer = MessageSerializer(data=data, context={'version_info': 55})
if serializer.is_valid():
message = serializer.save()
and in the serializer you can access the context with:
class MessageSerializer(serilizer.Serializer):
def create(self, validated_data, **kwargs):
version_info = self.context['version_info']
# do something …
message = Message.objects.create(**validated_data)
return message
Popping the element from the validated_data
Another option where you still call .save(version_info=55) is popping the data from the validated data with:
class MessageSerializer(serilizer.Serializer):
def create(self, validated_data, **kwargs):
version_info = validated_data.pop('version_info', None)
# do something …
message = Message.objects.create(**validated_data)
return message
this will return None for the version_info if you did not call it with .save(version_info=55).
