Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Django, how can I inherit a model that's not abstract as if it were abstract, so that I get a single table in the DB?

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

like image 548
HostedMetrics.com Avatar asked Oct 01 '15 04:10

HostedMetrics.com


People also ask

Can you inherit from a non abstract class?

An abstract class cannot be inherited by structures. It can contain constructors or destructors. It can implement functions with non-Abstract methods. It cannot support multiple inheritances.

How do you inherit models in Django?

Models inheritance works the same way as normal Python class inheritance works, the only difference is, whether we want the parent models to have their own table in the database or not. When the parent model tables are not created as tables it just acts as a container for common fields and methods.

What is abstract inheritance in Django?

An abstract model is a base class in which you define fields you want to include in all child models. Django doesn't create any database table for abstract models. A database table is created for each child model, including the fields inherited from the abstract class and the ones defined in the child model.

Which below option is the inheritance style in Django?

Proxy Model Inheritance: You Inherit from base class and you can add your own properties except fields.


2 Answers

Try to create an intermediate abstract model and inherits from your third party model

    ThirdPartyModelClass(models.Model):
        #fields goes here

    AbstractThirdPartyModelClass(ThirdPartyModelClass):

       class Meta:
           abstract = True


    YourModel(AbstractThirdPartyModelClass,models.Model):
        #your fields
like image 145
levi Avatar answered Oct 10 '22 12:10

levi


Also you can make a model with additional fields which will connect to the 'base' model by OneToOne relation. Using signals you can implement logic which will guarantee that every third-party model instance has 'extension' model instance created and connected.

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

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

like image 20
Igor Pomaranskiy Avatar answered Oct 10 '22 12:10

Igor Pomaranskiy