djangoinheritancemulti-table

Django Multi-table inheritance: specify custom one-to-one column name


I'm trying to create a Django ORM mapping that's compatible with an existing data model, so I'm trying to work with an existing set of table and column names.

I've got a multi-table inheritance situation where a class InformationObject derives from class Object. I'd like to let Django handle this the usual way:

class Object(models.Model):
    class Meta:
        db_table = "object"          

class InformationObject(Object):
    class Meta:
        db_table = "information_object"

In this case Django would automatically create a one-to-one field on the inheriting model called object_ptr_id. However, on the schema I'm constrained to use, the reference to the Object is simply called "id". So:

Is there a way to somehow specify the name of the column Django auto-magically uses for multi-table inheritance?

The alternative, which I'll have to use otherwise, is to use an explicit one-to-one field, but then I won't be able to inherit non-database methods from the Object model:

class Object(models.Model):
    class Meta:
        db_table = "object"          

class InformationObject(models.Model):
    class Meta:
        db_table = "information_object"
    id = models.OneToOneField(Object, primary_key=True, db_column="id")  

Any ideas? Maybe I could create a common base class for both of them and put non-db methods there...?


Solution

  • From the django docs (latest stable version):

    As mentioned, Django will automatically create a OneToOneField linking your child class back any non-abstract parent models. If you want to control the name of the attribute linking back to the parent, you can create your own OneToOneField and set parent_link=True to indicate that your field is the link back to the parent class.