Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compound/Composite primary/unique key with Django

How can you create models (and thus tables) with a compound (composite) primary/unique key using Django?

like image 898
Viet Avatar asked Feb 16 '10 05:02

Viet


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 multiple primary keys?

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

Can Django model have two primary keys?

Currently, Django models only support a single-column primary key. If you don't specify primary_key = True for the field in your model, Django will automatically create a column id as a primary key. The attribute unique_together in class Meta is only a constraint for your data.


2 Answers

Django does not support compound primary keys. You can create a single compound unique key with Meta.unique_together.

like image 156
Ignacio Vazquez-Abrams Avatar answered Sep 28 '22 07:09

Ignacio Vazquez-Abrams


if you want only unique mixed fields together use belowcode:

class MyTable(models.Model):     class Meta:         unique_together = (('key1', 'key2'),)      key1 = models.IntegerField()     key2 = models.IntegerField() 

But if you want unique together and one of column be primary, set primary argument for model column, similar below code:

class MyTable(models.Model):     class Meta:         unique_together = (('key1', 'key2'),)      key1 = models.IntegerField(primary_key=True)     key2 = models.IntegerField() 
like image 29
M.javid Avatar answered Sep 28 '22 07:09

M.javid