djangodjango-rest-frameworkdjango-signals

DRF PUT on Viewset/Serializer does not fire post_save signal on model instance


I have the following DRF viewset:

class MyViewSet(RetrieveModelMixin, ListModelMixin, UpdateModelMixin, GenericViewSet, CreateModelMixin, DestroyModelMixin):
        serializer_class = MySerializer
        queryset = My.objects.all()
        lookup_field = "uuid"

The following Serializer:

class MySerializer(serializers.ModelSerializer):
    class Meta:
        model = My
        fields = [
            'uuid',
            'name'
        ]

I have a signal stored in signal.py in the app

@receiver(post_save, sender=My)
def my_updated(sender, instance, created, **kwargs):
    if not created:
        print('MySignal Fired')

The signal is imported in apps.py. The signal is working when I open a terminal and run the .save() method on a instance.

The app is also declared in the django config. Any ideas?

BTW. when executing the .PUT on the API it saves everything nicely in the DB. So the api is doing it's work. Not sure why the signal is not firing though.


Solution

  • post_save does not work on put and patch request..

    The new functions to hook on generic views are:

    perform_create(self, serializer) - Called by CreateModelMixin  when saving a new object instance.
    perform_update(self, serializer) - Called by UpdateModelMixin when saving an existing object instance.
    perform_destroy(self, instance) - Called by DestroyModelMixin when deleting an object instance.
    

    See the docs.

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)
    
    def perform_update(self, serializer):
        instance = serializer.save()