Categories
Django Python

Extending Django’s Model.save() Method

I’m currently working on a project where I have a model named ‘Instructor’ with a few fields:

  • first_name – CharField
  • last_name – CharField
  • departments – Many-toMany

I found out at some point that I’d really like a field called “full_name”, which is “first_name” and “last_name” concatenated together. I didn’t want to have to fill the field in though, I wanted it to happen automatically. To accomplish this, I extended Django’s Model.save() method after I added the ‘full_name’ column to my model.

class Instructor(models.Model):
    first_name = models.CharField(max_length=150)
    last_name = models.CharField(max_length=150)
    departments = models.ManyToManyField(Department)
    full_name = models.CharField(max_length=180, blank=True)
 
    def save( self, *args, **kw ):
        self.full_name = '{0} {1}'.format( self.first_name, self.last_name )
        super( Instructor, self ).save( *args, **kw )

And that’s it! Now every time I create a new instructor with ‘first_name’ and ‘last_name’, it automatically populates the ‘full_name’ field for me.

By Jack Slingerland

Founder of Kernl.us. Working and living in Raleigh, NC. I manage a team of software engineers and work in Python, Django, TypeScript, Node.js, React+Redux, Angular, and PHP. I enjoy hanging out with my wife and son, lifting weights, and advancing Kernl.us in my free time.