Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the old values of django model field while updating without using signals in django rest framework?

I am using django-rest-framework. I have a case in which I need to update the field of other model once instance of first model is created or updated.

here is my models.py:

class FirstModel(models.Model):
    first_model_item = models.ForeignKey(Item)
    quantity =  models.IntegerField()

class SecondModel(models.Model):
    second_model_item = models.ForeignKey(FirstModel)
    quantity = models.IntegerField()

Here is my views.py:

class CreateSecondModelView(generics.CreateAPIView):
    permission_classes = ()
    queryset = SecondModel.objects.all()
    serializer_class = SecondModeSerializer

    def perform_create(self, serializer):
        instance = serializer.save()
        first_model_item = instance.item
        first_model_item.quantity -= instance.quantity
        first_model_item.save()


class UpdateSecondModelView(generics.RetrieveUpdateAPIView):
    permission_classes = ()
    queryset = SecondModel.objects.all()
    serializer_class = SecondModeSerializer

    def perform_update(self, serializer):
        instance = serializer.save()
        #here i want old value of quantity before updating.
like image 857
Asif Akhtar Avatar asked Dec 24 '22 09:12

Asif Akhtar


1 Answers

The serializer has an instance attribute, which is not updated until you call save. So:

old_quantity = serializer.instance.quantity
instance = serializer.save()
new_quantity = instance.quantity
like image 167
Daniel Roseman Avatar answered Apr 06 '23 10:04

Daniel Roseman