I have a legacy db table which has composite primary key. I don't think I will be able to change the structure to include a surrogate key, as there is some code written that uses that table. And in django, I cannot use that table, as it doesn't have a primary key(non-composite).
Do django models support composite primary keys? If not, is there any workaround without changing the structure of the table?
P.S. I am using postgresql.
Django does not support composite primary keys.
To add composite primary key in Python Django, we can set the unique_together field in the Meta class in the model class. to set unique_together to (('key1', 'key2'),) to make key1 and key2 part of the composite primary key.
Do Django models support multiple-column primary keys? ¶ No. Only single-column primary keys are supported.
A Composite Primary Key is created by combining two or more columns in a table that can be used to uniquely identify each row in the table when the columns are combined, but it does not guarantee uniqueness when taken individually, or it can also be understood as a primary key created by combining two or more ...
Try similar below code:
class MyTable(models.Model): class Meta: unique_together = (('key1', 'key2'),) key1 = models.IntegerField(primary_key=True) key2 = models.IntegerField()
or if you want only unique mixed fields:
class MyTable(models.Model): class Meta: unique_together = (('key1', 'key2'),) key1 = models.IntegerField() key2 = models.IntegerField()
EDIT: I would like to note that there is a problem with this approach if there are 3 columns. Update queries don't work because it tries to update (puts pk fields right after "SET") the fields that are unique together and obviously fails.
The accepted answer is fine. However, it's a little old. unique_together
may be deprecated in favor of UniqueConstraint. So, the better way of doing this would be;
UniqueConstraint(fields = ['key1', 'key2'], name = 'constraint_name')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With