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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With