jueves, 12 de enero de 2012

Automatically modifing data from models in django

If you want Django to automatically  add new data, update existing data or delete from a model you got various choices with various pros and cons.
This post will attempt to give you the necesary information to decide whats the best strategy, you can see how they are implemented in each of the provided links.
You basically have 3 options:



Signals 
The good
Signals is the most flexible way to work with your models, you can do pretty much anything at anytime with signals.
The bad
Because they get sent all the time and with many arguments, you might have to do many checks to know if you need them in that particular time and that migh easily lead to unnecessary code, and if you forget some check, your database will suffer.
Conclusion
Use them as your last resort,when the other options do not cut it, go for signals.

Overriding the save and/or the delete method in model classes
The good
This will run EVERY time a model is deleted or saved, you will never miss a chance to change your model data.
The bad
It can lead to hard to track bugs, if the operations you are doing inside the method assume too many things. This can be dangerous, and you might not now the time you are writing them how are you going to use your models.
Conclusion
Go safe with this one, only use things you are sure will always be available at the point of the save method. And try not to change other models data.

Overriding the save_model/delete_model/save_formset methods inside your model_admin class
The good
These methods are only called when you do things in your admin, so this are pretty safe to use, and allow you provide additional features and automation to your admin interface.
The bad
Limited use, won't do anything outside the admin.

No hay comentarios:

Publicar un comentario