In Django, how can I inherit a model that is not abstract, as if it were abstract, so that I get one table in the database?

Let's say I have a third-party model and it is not marked as abstract. I want to inherit it, add my own fields on top of this, and all this will be one table in the database. This usually means that I should inherit from an abstract model class, but in this case I don't have that luxury. Is there a way to have an intermediate step that creates an abstract class from the parent, so I can inherit it instead?

+4
source share
2 answers

Try creating an intermediate abstract model and inherit from your third-party model

    ThirdPartyModelClass(models.Model):
        #fields goes here

    AbstractThirdPartyModelClass(ThirdPartyModelClass):

       class Meta:
           abstract = True


    YourModel(AbstractThirdPartyModelClass,models.Model):
        #your fields
+1
source

You can also create a model with additional fields that will be connected to the "base" model by the ratio OneToOne. Using signals, you can implement logic that ensures that every instance of a third-party model has an extension model instance and is connected.

I mean something like the old recommended way to extend the Django model User:

https://docs.djangoproject.com/en/1.8/topics/auth/customizing/#extending-the-existing-user-model

+1
source

Source: https://habr.com/ru/post/1609744/


All Articles