'How to get a CharField's value as a string inside the model class?

class Comment(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='commenter', null=True)
    txt = models.CharField(max_length=1000, null=True)
    
    summary = str(txt)[:30] + '...'

How can I get the txt's value as a string and save it in summary? The code above returns something like this as a string: <django.db.models.fields.CharF...



Solution 1:[1]

You don't have to save txt to summary unless necessary. You can use a class method or property of a class to get the summary.

class Comment(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='commenter', null=True)
    txt = models.CharField(max_length=1000, null=True)
    
    def get_summary(self):
        return str(self.txt)[:30] + '...'

    @property
    def summary(self):
        return str(self.txt)[:30] + '...'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ashin Shakya