[Answer]-Django, defining extra model fields on db level instead of programming level

1👍

Could you create a new database field and then overwrite the save method to populate that field? I do that often to create a marked up version of a text field. For example:

class Dummmy(models.Model):
    content = models.TextField()
    content_html = models.TextField(editable=False, null=True)

    def save(self, *args, **kwargs):
        self.content_html = markdown(self.content)
        super(Dummmy, self).save(*args, **kwargs)

So for you:

class MyClass(models.Model):
    my_field = models.CharField(max_length=50)
    my_extra_field = models.CharField(editable=False, null=True)

    def save(self, *args, **kwargs):
        self.my_extra_field = self.my_field + 'extra value'
        super(MyClass, self).save(*args, **kwargs)
👤Kinsa

Leave a comment