Ok so I have a table named Courses where CourseCode and Pattern act as composite primary key. Now in another table called delivery_methods same CourseCode and pattern should act as foreign key for their respective attributes in table Courses. So how can I do that in django model
-
You can not have composite primary keys in Django, that is, at the moment, one f the limitations. – Willem Van Onsem Sep 12 '19 at 15:13
-
Possible duplicate of [Composite primary key in django](https://stackoverflow.com/questions/28712848/composite-primary-key-in-django) – dani herrera Sep 12 '19 at 15:27
-
but what about foreign keys. How I can declare CourseCode and Pattern in second table as foreign keys refering to 1st table – Amogh Kulkarni Sep 12 '19 at 16:13
-
@AmoghKulkarni actually the idea of implementing foreign keys to such composite primary keys are one of the the *main* reasons why they did not implement that. – Willem Van Onsem Sep 12 '19 at 16:53
2 Answers
I don't think it is possible to have a composite primary key. However, what I would do is the following:
Use the default primary key field that django assigns, then set the CourseCode and Pattern to be unique together (see here). This still will require each database entry to have these two fields as unique together.
You could then use the default primary key as foreign key in the delivery_methods table.

- 1
- 3
Unfortunately django does not support composite(compound or multi-column) keys. But, There is a third party library https://django-composite-foreignkey.readthedocs.io/en/latest/quickstart.html#example-simple-composite-foreignkey-models for it.
I found several useful links:
https://django-composite-foreignkey.readthedocs.io/en/latest/quickstart.html#example-simple-composite-foreignkey-models
Working with composite primary key in django project with legacy database
https://github.com/onysos/django-composite-foreignkey
https://code.djangoproject.com/wiki/MultipleColumnPrimaryKeys

- 170
- 9