django - Doing X when model is saved -


When Django's model is saved, then what is the correct way to do x? Let me try to explain it :)

For example, I have a model that is responsible for blog articles, if I am not set already, then I want to use the title field to generate the Slug field. Must be saved before saving. This is how I have achieved this time

  save def (own, * args, ** kwargs):. If self.slug == '': self.slug = slugify (self .title) super (paragraph, self). Save (* Args, ** kwargs)   

Is there any other way to do this? Is it better than other ways, how?

Thanks in any advice!

The most appropriate way is to override the clean method of your model: Django.template import defaults by filter class paragraph (models.Model): ... def define (self): if self.slug.strip () == '': self.slug = Defaultfilters.slugify (self.title) super (paragraph, self). Clean ()

This method will be called before saving the model, and any specificity is done before the check, so if there is a problem, it will still be caught.

You can read about the clean model of the model

Comments