Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Overriding Model Clean() vs Save()

I have a couple of actions to perform when saving a models, especially from the admin. I capitalize a couple of fields and check to make sure that either one field or the other is filled. I also create the field slug. RIght now these are split between overriding the clean and the save functions. It works now, but I am curious on when to use each. I looked through the docs, and I couldn't find specifically which to use when.

like image 406
saul.shanabrook Avatar asked Jan 28 '12 19:01

saul.shanabrook


People also ask

How do I override model save in Django?

Whenever one tries to create an instance of a model either from admin interface or django shell, save() function is run. We can override save function before storing the data in the database to apply some constraint or fill some ready only fields like SlugField.

Does Django save call clean?

save() calls the clean. This way the integrity is enforced both from forms and from other calling code, the command line, and tests. Without this, there is (AFAICT) no way to write a test that ensures that a model has a FK relation to a specifically chosen (not default) other model.

What is clean method in Django?

The clean() method on a Field subclass is responsible for running to_python() , validate() , and run_validators() in the correct order and propagating their errors. If, at any time, any of the methods raise ValidationError , the validation stops and that error is raised.


1 Answers

You should use clean to do validation-related work, and to parse/change/otherwise clean the input. Capitalizing fields and generating a slug can happen here. I also use clean to force a field like post_type to a specific value in proxy models. If you raise django.core.exceptions.ValidationError('error text') inside clean, the 'error text' is added to the form.non_field_errors.

Save is the place to change the way a model is actually saved. For instance, I've used save to create a crop of an uploaded picture. ValidationErrors are not caught if raised here, and I feel like that's the most important practical difference between the two.

like image 56
dokkaebi Avatar answered Sep 28 '22 13:09

dokkaebi