Reputation: 525
I am using Django 1.9, and now trying to override save
method behaviour. The problem is that when I do instance.some_field = some_value
, the self
object is already modified, whereas I need to know that was the original value of some_field
. To do this, the only way out seems to be fetching object from database by self
's pk.
So I wonder what is GENERIC syntax - if there's any - to fetch instance from the database? By saying GENERIC, I imply that I don't want to explicitly type the model name (like MYMODEL.objects.get(...)
), but rather make Django figure out the right model based on target instance's model.
To make the question clearer, let me illustrate my goal in a pseudo-code:
def save_extented(self, *args, **kwargs):
original_object = (self model).objects.get(pk = self.pk)
Is it possible ? Or maybe I don't need this, and there's some smart Django hack to fetch the instance with rolled back field values ?
Upvotes: 0
Views: 326
Reputation: 527
You can use django-dirtyfields and pre_save
signal:
@receiver(pre_save, sender=MyModel)
def pre_save_logic(sender, instance, **kwargs):
if 'my_field' in instance.get_dirty_fields():
do_some_logic()
Upvotes: 1