I try to use some fields in my django models when they are saved. Looking at this question that this answer was:
class Blog(models.Model): name = models.CharField(max_length=100) def save(self): self.name = self.name.title() super(Blog, self).save()
This works great, however in each save it requires some extra typing if I want to repeat this several times. Therefore, I would like to create a function that takes fields as input and saves them as uppercase during the save step. So I wrote this to check it out:
def save(self): for field in [self.first_name, self.last_name]: field = field.title() super(Artist,self).save()
However, if I had thought about this earlier, I would have realized that this simply overwrites the field variable. I want to cycle through a list of variables to change them. I know that some functions change the value in place without using = . How do they do it? Can i achieve this?
Or is there some simpler way to do what I'm doing? Am I mistaken?
SOLUTION: From the first answer, I made a function:
def cap(self, *args): for field in args: value = getattr(self, field) setattr(self, field, value.title())
and in my models:
def save(self): cap(self,'first_name', 'last_name') super(Artist,self).save()
source share