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?
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.
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.
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.
Proxy Model Inheritance: You Inherit from base class and you can add your own properties except fields.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With