Style - When to serialize a Django model Instance: signals vs model's save method

StackOverflow https://stackoverflow.com/questions/131327

  •  02-07-2019
  •  | 
  •  

Question

I plan to serialize a Django model to XML when it's saved or updated. (The XML's going to be imported into a flash movie). Is it better to listen for a post_save() or pre_save() signal and then perform the serialization, or to just handle it in the model's save() methon

Was it helpful?

Solution

If it's core functionality for saving the model you'll want it as part of the save method. However, if you already have a functioning model and you want to extend it for other purposes then signals are your best bet since they allow for properly decoupled modules.

A good example might be that you want to add event logging to your site, so you simply listen for the signals that signify an event rather than modifying the original site code.

post_save() is usually best because it means the model has been successfully saved, using pre_save() doesn't guarantee that the save will be successful so shouldn't be used for anything that would depend on the save being completed.

OTHER TIPS

Post save. That way the new data (the reason for performing the serialization) is already in the database. It'll make for a much cleaner bit of code that simply takes from the database and doesn't have to worry about adding an extra value.

The other way that comes to mind is to maintain the xml file in parallel to the database. That is to say, in your save() add the data to the database, and to the xml file. This would have a much less overhead if you're dealing with huge tables.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top