Most of the time, people don’t actually need their composite (multi-column) key to be the primary key.
Django operates best with surrogate keys – that is, it automatically defines an autoincrement field called id and sets that to be the primary key. That is suitable for almost all the users.
If you then need to enforce a unique constraint on your model across two or more fields, you can use the unique_together setting in the inner Meta class.
class Student(models.Model): Name = models.CharField(max_length=100) Roll = models.CharField(max_length=20) Department = models.CharField(max_length=15) class Meta: unique_together = (('Roll', 'Department'),)
It would act as a surrogate primary key column.
Sets of field names that, taken together, must be unique:
unique_together = (('Roll', 'Department'),)
This is a tuple of tuples that must be unique when considered together. It’s used in the Django admin and is enforced at the database level (i.e., the appropriate UNIQUE statements are included in the CREATE TABLE statement).
For convenience, unique_together can be a single tuple when dealing with a single set of fields :
unique_together = ('Roll', 'Department')