Django Model Field Default Based Off Another Field in Same Model

Models certainly do have a “self”! It’s just that you’re trying to define an attribute of a model class as being dependent upon a model instance; that’s not possible, as the instance does not (and cannot) exist before your define the class and its attributes.

To get the effect you want, override the save() method of the model class. Make any changes you want to the instance necessary, then call the superclass’s method to do the actual saving. Here’s a quick example.

def save(self, *args, **kwargs):
    if not self.subject_init:
        self.subject_init = self.subject_initials()
    super(Subject, self).save(*args, **kwargs)

This is covered in Overriding Model Methods in the documentation.

Leave a Comment