Pala
Pala

Reputation: 63

Django multi-table inheritance with separate (identical) tables without pointers

I'm subclassing an existing model (from another application entirely) and want my model to have its own database table. An identical clone/replica of the original table, not just a table with a pointer to the data stored in the "parent" table.

Here's my model:

class A (models.Model):
    name = models.CharField('name')

class MyA (A):
    class Meta:
        db_table = 'My_A'

Here's my DB tables:

CREATE TABLE A
(
  id serial NOT NULL,
  "name" character varying(50) NOT NULL,
  ...
)

CREATE TABLE My_A
(
  A_ptr_id integer NOT NULL,
  ...
)

And here's what I would like to have:

CREATE TABLE A
(
  id serial NOT NULL,
  "name" character varying(50) NOT NULL,
  ...
)

CREATE TABLE My_A
(
  id serial NOT NULL,
  "name" character varying(50) NOT NULL,
  ...
)

Edit: I ended up copy-pasting the 3rd party model

Upvotes: 6

Views: 2274

Answers (3)

Benargee
Benargee

Reputation: 171

If I am understanding you correctly, you can create an abstract base class that won't have its own table. From there you could then create multiple classes that inherit from that base class that have their own tables.

class ABase(models.Model):
    name = models.CharField('name')
    class Meta:
        abstract = True

class A(ABase):
    class Meta:
        db_table = 'A'

class MyA(ABase):
    class Meta:
        db_table = 'My_A'

Django 2.2 Documentation - Abstract base classes

Upvotes: 4

schacki
schacki

Reputation: 9533

New approach (if you insist on separating the data): create model MyA without inheriting from A and create another model MergeA that creates explicit generic foreign key to My and A. But this will certainly require quite some extra coding.

Upvotes: 0

schacki
schacki

Reputation: 9533

When you inherit a Django Model it will always generate an implict 1-1 relation to the parent model. And Django will only generate the fields for your inherited model. Which in general makes total sense to me. But for your use case is cumbersome. Since we are taling about Django core functionality, it might be hard to workaround. You could try to copy and paste your 3rd party model into your code as a proxy model and inherit from there.

Update: But why do you want to separate the data into different tables? What is the final objective?

Upvotes: -1

Related Questions