Compound/Composite primary/unique key with Django
Solution 1
Django does not support compound primary keys. You can create a single compound unique key with Meta.unique_together
.
Solution 2
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()
Solution 3
A composite key consists of more than one attribute to uniquely identify an entity occurrence. This differs from a compound key in that one or more of the attributes, which make up the key, are not simple keys in their own right.
For example, you have a database holding your CD collection. One of the entities is called tracks, which holds details of the tracks on a CD. This has a composite key of CD name, track number.
Viet
Developer who is passionate about web, C++, design, classical music, art and tries mixing them together.
Updated on July 09, 2022Comments
-
Viet almost 2 years
How can you create models (and thus tables) with a compound (composite) primary/unique key using Django?