How can you create models (and thus tables) with a compound (composite) primary/unique key using Django?
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.
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.
Django does not support compound primary keys. You can create a single compound unique key with Meta.unique_together
.
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()
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