tags:

views:

606

answers:

2

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

A: 

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.

defrex
"Data already in the database" doesn't make the code any cleaner. Either way you want to pull the data from the model object, you don't make an extra trip to the DB. Post_save is the right answer, but @Andrew Ingram has the correct reason.
Carl Meyer
+1  A: 

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.

Andrew Ingram