[Fixed]-Django or similar for composite primary keys

20👍

A work around is to create a surrogate key (an auto increment column) as the primary key column and place a unique index on your domain composite key.

Foreign keys will then refer to the surrogate primary key column.

24👍

Why not add a normal primary key, and then specify that part_number and part_revision as unique_together?

This essentially is the Djangoish (Djangonic?) way of doing what Mitch Wheat said.

14👍

I strongly suggest using a surrogate key. Not because it is “Djangoesque”. Suppose that you use a composite key that includes part_number. What if some time later your company decides to change the format (and therefore values) of that field? Or in general terms, any field? You would not want to deal with changing primary keys. I don’t know whatever benefit you see in using a composite key that consists of “real” values, but I reckon it isn’t worth the hassle. Use meaningless, autoincremented keys (and that should probably render a composite key useless).

👤shanyu

2👍

SQLAlchemy has support for composite primary and foreign keys, so any SQLAlchemy based framework (Pylons and Werkzeug comes to mind) should suite your needs. But surrogate primary key is easier to use and better supported anyway.

Leave a comment