reedvoid
reedvoid

Reputation: 1253

Django: inheritance creates foreign keys?

I'm reading someone else's Django code, using PostgreSQL, and this is something I don't understand.

It seems that, when this code defines a class from another, a foreign key to that class is created within this one. I don't really understand why there would be a connection between the two, seems like inheritance and foreign keys are completely different concepts.

Here's a bit of code, the class is Contractor, which inherits from auth.User - which is a custom class created elsewhere in the project.

class Contractor(lancer.auth.User):
    a = models.xxxx
    b = models.xxxx
    .... 

After I syncdb on that, the database shows something like this,

CREATE TABLE lancer_contractor
(
    user_ptr_id integer NOT NULL,
    a integer,
    b text NOT NULL,
    .... 

    CONSTRAINT lancer_contractor_pkey PRIMARY KEY (user_ptr_id ),
    CONSTRAINT lancer_contractor_user_ptr_id_fkey FOREIGN KEY (user_ptr_id)
        REFERENCES lancer_user (id) MATCH SIMPLE
        ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED
)

From this SQL code I understand 2 things,

  1. Somehow there's a foreign key created inside the Contractor table pointing to the User table
  2. That foreign key is also the primary key for Contractor

After some testing with some other random classes I can confirm that this always happens. What is going on here? Why are foreign keys getting mixed up with inheritance?

Thanks!

Upvotes: 0

Views: 261

Answers (1)

Evan Brumley
Evan Brumley

Reputation: 2468

Multi-table inheritance

Upvotes: 1

Related Questions