Setting an instance of multiple field joint unique constraints in Django model

  • 2021-07-22 10:13:37
  • OfStack

When using Django, we encounter such a requirement that several fields of a table are indexed by joint only one. For example, two fields in the student table, name and class, represent a only one record from one.

The model section of Django is described in the unique-together section.


class MyModel(models.Model):
 field1 = models.CharField(max_length=50)
 field2 = models.CharField(max_length=50)

 class Meta:
 unique_together = ('field1', 'field2',)

Corresponds to SQL in MySQL, similar to the following statement


CREATE UNIQUE INDEX index_name ON tablename(field1, field2);

Related articles: