Home > other >  After overriding create function, how to the get the id of the newly created object in django?
After overriding create function, how to the get the id of the newly created object in django?

Time:01-25

I have a ModelViewSet and I want to perform some more operations on the newly created object. But I am unable to get the newly created object id here. How to get the newly created object id after the super()?

    def create(self, request, *args, **kwargs):
        phone = request.data.get('student_phone_number')
        batch_id = request.data.get('batch_id')
        class_number = request.data.get('class_number')
        if not any([phone, batch_id, class_number]):
            return Response({"message": "Missing Params"}, status=status.HTTP_400_BAD_REQUEST)

        if self.queryset.filter(student_phone_number=phone, batch_id=batch_id, class_number=class_number,
                                is_cancelled=False).exists():
            return Response({"message": "Compensation class already booked"}, status=status.HTTP_400_BAD_REQUEST)
        
        super().create(request, *args, **kwargs)

CodePudding user response:

you should overwrite the perform_create not create Method on ModelViewSet

def perform_create(self, serializer):
    phone_value = self.request.data['phone']
    batch_id_value = self.request.data['batch_id']
    class_number_value = self.request.data['class_number']

    // do your condition here

    instance = serializer.save(phone=phone_value, batch_id=batch_id_value, class_number=class_number_value)
    
    instance_id = instance.id

    // do whatever you want with instance_id 

    return Response({"message": "Data Has been saved", Id:instance_id }, status=status.HTTP_201_CREATED)
    

Calling serializer.save() should return the instance that has just been create.

  •  Tags:  
  • Related