[Answered ]-How to pass arguments to model save method in django through serializer create method

1👍

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).

Leave a comment