[Django]-Django Models: Automatic value assignment to a field based on another field value

2👍

I don’t think you should be adding fields to the database just to make nice filters in the admin.

Regardless, your problem is that you’re not assigning first_char to the value of the object, but to a CharField, which isn’t subscriptable, just as the error tells you. I would suggest going through the tutorial and learning more, but here is an answer to your question.

Override the save() method, and add the field there:

class Question(models.Model):
    ...
    first_char = models.CharField(max_length=1)

    def save(self):
        # self.first_char for referencing to the current object
        self.first_char = self.question_text[1]
        super().save(self)

Now, whenever the object is saved, first_char will be set to the first character of the question_text.

Leave a comment