Sometimes, we want to add composite primary key in Python Django.
In this article, we’ll look at how to add composite primary key in Python Django.
How to add composite primary key in Python Django?
To add composite primary key in Python Django, we can set the unique_together
field in the Meta
class in the model class.
For instance, we write
class MyTable(models.Model):
class Meta:
unique_together = (('key1', 'key2'),)
key1 = models.IntegerField(primary_key=True)
key2 = models.IntegerField()
to set unique_together
to (('key1', 'key2'),)
to make key1
and key2
part of the composite primary key.
Conclusion
To add composite primary key in Python Django, we can set the unique_together
field in the Meta
class in the model class.