Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get previous data of object in django save model method

Lets say we have an object myobj which has fields f1, f2. Initially the fields are set to 1 and 2 and saved having pk=1

Now, I am calling it again something like this:

myobj.f1 = 11
myobj.f2 = 22
myobj.save()

while the model method is save(self, *args, **kwargs) I know, we can pass our own variables to it, override the method, do what ever we want..

Is there anyway that we can know previous data of the object? using some built-in arguments?

like image 613
Surya Avatar asked Sep 05 '25 00:09

Surya


1 Answers

There isn't any built-in way to get old data in save() method. You will have to do query the db. Something like this:

class MyModel(Model):
   ...
   def save(self, *args, **kwargs):
       if self.pk:
          old_obj = MyModel.objects.get(pk=self.pk)

       #use old_obj for something

       ...
like image 172
Rohan Avatar answered Sep 08 '25 00:09

Rohan