Reputation: 3168
I am trying to capitalize a number of fields in my django models, when they are saved. Looking at this question, which had this answer:
class Blog(models.Model):
name = models.CharField(max_length=100)
def save(self):
self.name = self.name.title()
super(Blog, self).save()
This works fine, however, in each save, this requires some extra typing, if I want to repeat this multiple times. So I would like to create a function that takes fields as an input and re-saves them as uppercase, during the save step. So I wrote this to test it:
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 it before, I would have realized that this simply overwrite 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 the =
. How do they do this? Could I achieve that?
Or is there some simpler way to do what I am doing? I am going the wrong way?
SOLUTION: From the first answer, I made the 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()
Upvotes: 5
Views: 7157
Reputation: 55293
You can use setattr(self, my_field_name, value) to achieve this.
for field in ['first_name', 'last_name']:
value = getattr(self, field)
setattr(self, field, value.title())
You won't be able to modify the value in-place as strings are immutables in Python.
Upvotes: 7