How to compare old and new field values in Django serialiazer?

I have a Django model which has a many to many field. When adding or changing a record in this table, I need to perform certain actions. Because the table contains a many to many field, I can't perform model-level validation using the save method.(Correct me if I am wrong, but when i add or remove many to many field then save method on main table is not called)

So I'm trying to override the save method on the serializer.

def save(self, **kwargs):
    obj = super(PlanningExchangeRateSerializer, self).save(**kwargs)
    return obj

Can you please tell me how to determine whether any field values ​​have changed?

Yes, you can save or delete two objects in a single view. You need to override a method, not on the serializer but on the view.

Lets say you are using ModelViewSet, the Save and deletion hooks: provided by the Mixin classes allows you to override these methods.

    from rest_framework import viewsets
    from .serializers import MySerializer
    from .models import MyModel


    class MyModelViewSet(viewsets.ModelViewSet):
        serializer = MySerializer
        queryset = MyModel.objects.all()
        
        def perform_create(self, serializer):
            # do whatever you want with your relation fields
            serializer.save()

        def perform_update(self, serializer):
            # do whatever you want with your relation fields
            serializer.save()
        
        def perform_destroy(self, instance):
            # do whatever you want with your relation fields
            instance.delete()
Back to Top