[Django]-Inheritance model update to its parent model

0👍

Proxy models don’t add new tables. From the docs link you mentioned:

The MyPerson class operates on the same database table as its parent Person class.

If you want one table called core_city, and another called custom_city, the second one having an extra field, you simply subclass it. Perhaps it would be easier to use an alias:

from core.models import City as CoreCity

class City(CoreCity):
    newfield = models.CharField(max_length=20)

custom_city will have all fields from core_city, plus a newfield. The description of how this works (and an example) is covered in the docs section Multi-table inheritance.

If what you want is to have one single database table, then you should use a proxy Model, however they really don’t allow you to create new fields. The field should be created in the parent model, or otherwise exist in the database and not be handled by Django migrations at all.

0👍

You are looking for Abstract base classes models:

Abstract base classes are useful when you want to put some common information into a number of other models. You write your base class and put abstract=True in the Meta class.

This is the base class:

#core/models.py
class City(Master):
    zipcode = models.IntegerField()
    class Meta:
        abstract = True   # <--- here the trick

Here your model:

#custom/models.py
from core.models import City as CoreCity
class City(CoreCity):
    newfield = models.CharField(max_length=20)

For many uses, this type of model inheritance will be exactly what you want. It provides a way to factor out common information at the Python level, while still only creating one database table per child model at the database level.

0👍

You can update or create your class constants after its defined like this

from core.models import City    

City.newfield = models.CharField(max_length=20)
👤dtrckd

0👍

You may need to use swappable models, using them you can define a City class and change it with whichever model you need later,
but that way you can’t import and use the base City model directly, you may need to provide a method like get_city_model for that, as your public API.

class City(Master):
    zipcode = models.IntegerField()

    class Meta:
        swappable = 'CORE_CITY_MODEL'

and maybe replace it later with some other model, then just set CORE_CITY_MODEL to that model in the form of ‘app_name.model_name’.

The django.contrib.auth is a good example of this, you may consider checking User model and get_user_model method. Although I think you may face problems if you change your city model after you did run migrate, it may not move your data to the new table, but I’m not sure about this.

Leave a comment