Django REST serializer: create object without saving

If you're using a Generic View or using mixins.CreateModelMixin directly in your view, you may find yourself in a situation where you need to get access to the object in the perform_create method. You can use Moses Koledoye's idea to create the object without saving:

def perform_create(self, serializer):
    # Create an instance WITHOUT saving
    instance = self.model(**serializer.validated_data)
    # ... do more stuff with the instance
    # ...
    # THEN, if you need to save the instance later
    instance.save() 

This is opposed to having the line instance = serializer.save() in this perform_create method which gives you access to the instance but requires you to save it, which could be bad a few ways, such as

  • you need access to the model's methods before you can create the instance
  • you need the instance to exist to access to manipulate some of its data, so you have to save it twice

Add this method to your SearchRequestSerializer class

def create(self):
    return SearchRequest(**self.validated_data)

And call it in function post_calculation instead of save, like so:

mySearchRequestObject = serializer.create()