I'm wondering is it a good practice to have methods in Django model just for setting and saving values? For example I have a model:
class Team(models.Model):
name = models.CharField(max_length=50)
def set_name(self, name):
self.name = name
self.save()
I can set name outside of model like this:
team.name = name
team.save()
Or I can use set_name
method:
team.set_name(name)
In my understanding it is better to use set_name
method, because it is loosely coupled. For example if I'll change name of the name
field I won't need to update all references to this field in my codebase.
IMO it's better to call save outside a method on the model because often you'll be calling save
with more than one field changed. So if you were changing name
and date_last_active
, you wouldn't be using your set_name
method.
Django generally doesn't call save on the model methods for this reason. User.set_password()
is an example of this.
And, as others will say undoubtedly, use save(update_fields=['field_a', 'field_b'])
for efficiency.