Reputation: 307
I'm trying to find out how django's save() works. And there is some thing I can't understand. Is there any way to know what field is updating at the moment?
The best way I know is use pre_save() signal and do smth like this:
current_field_val = instance.my_field
old_field_val == sender.objects.get(pk=instance.pk).my_field
if current_field_val != old_field_val:
# do smth
But I don't want to select from DB. And how DjangoORM knows what field needs to be updated, or it updates all fields in the model(it seems to me it's strange behaviour).
Upvotes: 1
Views: 235
Reputation: 18691
In a view, you can use form.changed_data
to find out which data is changed in the form.
E.g.
if 'yourfield' in form.changed_data`:
(do something)
Upvotes: 1
Reputation: 5194
you can use something like this:
class myClass(models.Model):
my_field = models.CharField()
__my_field_orig = None
def __init__(self, *args, **kwargs):
super(myClass, self).__init__(*args, **kwargs)
self.__my_field_orig = self.my_field
def save(self, force_insert=False, force_update=False, *args, **kwargs):
if self.my_field != self.__my_field_orig:
# my_field changed - do something here
super(myClass, self).save(force_insert, force_update, *args, **kwargs)
self.__original_name = self.name
Upvotes: 0