5

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()

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.