I have a model that I would like to contain a subjects name and their initials. (The data is somewhat anonymized and tracked by initials.)
Right now, I wrote
name = models.CharField("Name", max_length=30)
return ''.join(map(lambda x: '' if len(x)==0 else x,
# Next line is what I want to do (or something equivalent), but doesn't work with
# NameError: name 'self' is not defined
subject_init = models.CharField("Subject Initials", max_length=5, default=self.subject_initials)
subject_init = models.CharField("Subject initials", max_length=2, default=subject_initials)
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.