Sunday, May 29, 2011

Re: signals pre_save vs model's save()

On 28 May 2011 11:05, Mateusz Harasymczuk <mateusz@harasymczuk.pl> wrote:
I am thinking about splitting my model's save() method over few signals.

For example, stripping spaces and making string capitalized.


Why would you want to do that?
 
I have even more sophisticated problems such as making an object field active set to False basing on various parameters from other fields, such as expiration date, or good or bad karma points.

What do you think, it is generally good idea, to keep models file clean out of heavily overloaded save() methods?


If this logic is tied to your model, what is the advantage of moving it out of the save() method in your model definition? 
You would more usefully serve the same purpose by decomposing the save() method into several functions e.g.:

def save(self,...):
    self._strip_chars()
    self._validate_and_set_fields()
    super(Model, self).save()

Clean, simple and makes it very obvious what you're doing in the save() method. Compare that with the signals version, which will give someone reading the code no clue at all that when they call save() the values of the fields will change.

How about making more than one signal pre_save to the same model?

It will work, but it's the wrong approach.

Malcolm

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment