views:

166

answers:

1

I'm mapping an existing database structure into Django models. I have a many-to-many structure where the association table is natural-keyed:

CREATE TABLE foo (id INTEGER PRIMARY KEY);
CREATE TABLE bar (id INTEGER PRIMARY KEY);
CREATE TABLE foo2bar (foo_id INTEGER REFERENCES foo(id),
                      bar_id INTEGER REFERENCES bar(id),
                      PRIMARY KEY (foo_id, bar_id)
                      );

Is there no way to get Django's ORM to map this? Must I change foo2bar to use a surrogate key? E.g.

CREATE TABLE foo2bar (id INTEGER PRIMARY KEY,
                      foo_id INTEGER REFERENCES foo(id),
                      bar_id INTEGER REFERENCES bar(id)
                      );
CREATE UNIQUE INDEX ix_foo2bar_uniq ON foo2bar (foo_id, bar_id);
+1  A: 

I don't think Django - as far as 1.1 - allows for composite primary keys like you want.

See: http://code.djangoproject.com/ticket/373

So, I would say that unless 1.2 (March 2010?) implements a fix for the ticket above, you will have to modify your database table.

celopes
Also worth reading: http://code.djangoproject.com/wiki/MultipleColumnPrimaryKeys
celopes
Looks conclusive enough for me — thanks!
Gunnlaugur Briem