1

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).

Vladimir Solovyov
  • 287
  • 1
  • 2
  • 11

2 Answers2

1

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)
SaeX
  • 17,240
  • 16
  • 77
  • 97
  • Oh, I didn't know that. It's better. Thanks. But it doesn't cover all needs sometimes. As Hasan Ramezani said - 'it is a good idea for contribution in django' :) – Vladimir Solovyov Dec 02 '14 at 21:00
0

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
Hasan Ramezani
  • 5,004
  • 24
  • 30
  • Thanks. I know this way too, I just want to find default solution. For example RoR orm allows this: `recod.title = "someothertitle"` `record.changes` `{"title"=>["sometitle", "someothertitle"]}` And also I want to know how Django acts. Is it updates all fields or it keeps somewhere fields to change..? And if it acts in the second way - why Django doesn't want to give to me that info :) – Vladimir Solovyov Dec 02 '14 at 20:43
  • @VladimirSolovyov yes dude your right :). it is a good idea for contribution in django :)) – Hasan Ramezani Dec 02 '14 at 20:48