Reputation: 18404
How can you create models (and thus tables) with a compound (composite) primary/unique key using Django?
Upvotes: 33
Views: 26665
Reputation: 6647
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()
Upvotes: 18
Reputation: 798884
Django does not support compound primary keys. You can create a single compound unique key with Meta.unique_together
.
Upvotes: 39