Django REST serializer: create object without saving

12,529

Solution 1

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

Solution 2

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
Share:
12,529

Related videos on Youtube

Botond
Author by

Botond

Updated on September 26, 2022

Comments

  • Botond
    Botond over 1 year

    I have started to play with the Django REST framework. What I am trying to do is to POST a request with some JSON, create a Django Model object out of it, and use the object without saving it. My Django model is called SearchRequest. What I have is:

    @api_view(['POST'])
    def post_calculation(request):
        if request.method == 'POST':
            #JSON to serializer object
            serializer = SearchRequestSerializer(data=request.data)
            if (serializer.is_valid() == False):
                return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
            mySearchRequestObject = serializer.save()
    

    This does create a SearchRequest object, however saves it into the database right away. I would need it without saving.

  • Botond
    Botond almost 8 years
    Thanks! Could you please explain it a little? I could only get it work with serializer.create(serializer.validated_data)
  • Moses Koledoye
    Moses Koledoye almost 8 years
    It unpacks your validated data and uses the resulting keyword arguments to instantiate the SearchRequest class. Just as you would have instantiated the class on a good django day
  • Botond
    Botond almost 8 years
    OK, I get it now. What I did was to change to return SearchRequest(**self.validated_data)