Django - Custom save method in model -


(using django 1.11.5)

traditionally, i've created model so:

class animal(models.model):     is_hungry = models.booleanfield(default=true) 

then make changes so:

animal = animal() animal.save()  animal.is_hungry = true animal.save() 

recently, saw friend define model custom save method:

class animal(models.model):     is_hungry = models.booleanfield(default=true)      def feed_animal(self):         self.is_hungry = false         self.save() 

and calling method appears work expected:

>>> testapp.models import animal >>> = animal() >>> a.save() >>> a.is_hungry true >>> >>> a.feed_animal() >>> a.is_hungry false 

are there benefits/drawbacks in defining such custom save method in model definition? there reason prefer calling .save() on object directly?

there's no drawbacks might not best practice have implicit saves buried model's methods. it'd cleaner define feed_animal method modifies state of model object , leave saving view.py code:

# model.py class animal(models.model):     is_hungry = models.booleanfield(default=true)      def feed_animal(self):         # makes sense if ther's more setting attribute         self.is_hungry = false  # view.py = animal() a.feed_animal() a.save() 

the pattern defining custom save methods understood in django overriding save method of model class in child class , make sense if need permamently change object behaviour on save:

# model.py class animal(models.model):     is_hungry = models.booleanfield(default=true)      def feed_animal(self):         # makes sense if ther's more setting attribute         self.is_hungry = false      # let need save fed animals     def save(self, *args, **kwargs):         self.feed_animal()                 super(model, self).save(*args, **kwargs) 

Comments

Popular posts from this blog

neo4j - finding mutual friends in a cypher statement starting with three or more persons -

php - How to remove letter in front of the word laravel -

minify - Minimizing css files -