Categories
Python Answers

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

Spread the love

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):
    pass

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

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *