Menu Close

How to override a parent model’s attribute with Python Django?

To override a parent model’s attribute with Python Django,. we can create a child model that inherits from the parent.

For instance, we write

class AbstractPlace(models.Model):
    name = models.CharField(max_length=20)
    rating = models.DecimalField()

    class Meta:
        abstract = True

class Place(AbstractPlace):

class LongNamedRestaurant(AbstractPlace):
    name = models.CharField(max_length=255)
    food_type = models.CharField(max_length=25)

to create the AbstractPlace model which has some fields shared between Place and LongNamedRestaurant.

Then in LongNamedRestaurant, we override the name field from AbstractPlace by setting name to a models.CharField(max_length=255) instead of models.CharField(max_length=20).

Posted in Python, Python Answers