Search code examples
pythondjangopython-3.xsignalsdjango-1.9

Django pre-save signal


I have a pre-save signal for one of my models. This pre-save signal does some background API activity to syndicate new and updated objects to service providers and return meaningless data for us to store as references in the places of the original data.

The new and update methods are different in the API.

Ideally, if a user were to perform an update they would be clearing the meaningless data from a field and typing over it. My signal would need to know which fields were updated to send changes for just those fields, as sending all fields in an update would send meaningless references as the raw data in addition to the updates.

The pre-save signal has the argument update_fields. I searched for some details and found that this argument may include all fields when an update is performed.


Regarding update_fields as the docs have little information on this

  • When creating an object, does anything get passed to update_fields?
  • When updating an object, do all fields get passed to update_fields, or just the ones that were updated?

Is there some other suggestions on how to tackle this? I know post_save has the created argument, but I'd prefer to operate on the data before it's saved.


Solution

  • When creating an object, does anything get passed to update_fields?

    No.

    When updating an object, do all fields get passed to update_fields, or just the ones that were updated?

    Depends who is calling the save() method. By default, Django doesn't set update_fields. Unless your code calls save() with the update_fields argument set, it will rewrite all the fields in the database and the pre_save signal will see update_fields=None.

    My signal would need to know which fields were updated to send changes for just those fields.

    Unless you are controlling what calls the save() method on the object, you will not get this information using update_fields. The purpose of that argument is not to let you track which fields have changed - rather it is to facilitate efficient writing of data when you know that only certain columns in the database need to be written.