djangoinheritancedjango-modelssingle-table-inheritance

Create Django abstract child model refering to the table of the parent model


I have a model (Parent) that has a table in the database (table app1_parent) in a first app (app1).

In another app (app2), I would like to add functionnality to this Parent model, but still refer to the existing Parent table (table app1_parent), which is part of the other app (app1).

If I create in app2 the Child model that simply inherite from Parent, I end up with two different tables: app1_parent and app2_child

I'd like to know if I can create an (abstract ?) child model (Child) that refers to the table of the Parent model, without adding additional field, but adding new methods and properties. (Basically I would want to do the contrary of what abstract tables have been built to do)

class Parent(models.Model):
    my_field = models.CharField(max_length=255)

class Child(Parent):
    
    def my_method(self):
        return 'done'

    class Meta:
        abstract = True

Is there another way to achieve my result?

PS: of course, the objective would be not to modify the app1.Parent model and app1.parent table


Solution

  • OK, I finally found a solution my own answer: using Django proxy models to achieve single-table inheritance:

    class Child(Parent):
        
        def my_method(self):
            return 'done'
    
        class Meta:
            proxy= True
    

    very good answer on how to expand single-table inheritance to have child models identified as "distinct" of the Parent model, and between them: https://stackoverflow.com/a/60894618/12505071