In my very simple learning application, I would like to trigger some logic the moment that a model changes to 'complete'. Specifically, I pass the following payload to my viewset:

{
   complete: true
}

which is as follows:

class TestQuestionViewset(viewsets.ModelViewSet):

    queryset = TestQuestion.objects.all()
    serializer_class = TestQuestionSerializer

I would like to trigger some logic server side that is triggered as soon as the complete flag is updated.

Could I override the update method? If so, how could I do this?

1 Answers

1
JPG On Best Solutions

try this

class TestQuestionViewset(viewsets.ModelViewSet):
    queryset = TestQuestion.objects.all()
    serializer_class = TestQuestionSerializer

    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        if partial:
            old_complete_value = instance.complete
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)

        if partial and old_complete_value is False:
            instance.refresh_from_db()
            if instance.complete:
                ...
                # do your logic here

        if getattr(instance, '_prefetched_objects_cache', None):
            # If 'prefetch_related' has been applied to a queryset, we need to
            # forcibly invalidate the prefetch cache on the instance.
            instance._prefetched_objects_cache = {}

        return Response(serializer.data)