Surya Kasturi
Surya Kasturi

Reputation: 4741

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?

Upvotes: 4

Views: 2035

Answers (1)

Rohan
Rohan

Reputation: 53336

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

       ...

Upvotes: 6

Related Questions