Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Composite primary key in django

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.

like image 566
khajvah Avatar asked Feb 25 '15 06:02

khajvah


People also ask

Does Django support composite primary key?

Django does not support composite primary keys.

How do I add a composite primary key in Django?

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.

Does Django support multi column primary key?

Do Django models support multiple-column primary keys? ¶ No. Only single-column primary keys are supported.

What is a composite primary key?

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 ...


2 Answers

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.

like image 160
M.javid Avatar answered Sep 18 '22 12:09

M.javid


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') 
like image 21
TechniCollins Avatar answered Sep 18 '22 12:09

TechniCollins