How to define two fields "unique" as couple How to define two fields "unique" as couple django django

How to define two fields "unique" as couple


There is a simple solution for you called unique_together which does exactly what you want.

For example:

class MyModel(models.Model):  field1 = models.CharField(max_length=50)  field2 = models.CharField(max_length=50)  class Meta:    unique_together = ('field1', 'field2',)

And in your case:

class Volume(models.Model):  id = models.AutoField(primary_key=True)  journal_id = models.ForeignKey(Journals, db_column='jid', null=True, verbose_name = "Journal")  volume_number = models.CharField('Volume Number', max_length=100)  comments = models.TextField('Comments', max_length=4000, blank=True)  class Meta:    unique_together = ('journal_id', 'volume_number',)


Django 2.2+

Using the constraints features UniqueConstraint is preferred over unique_together.

From the Django documentation for unique_together:

Use UniqueConstraint with the constraints option instead.
UniqueConstraint provides more functionality than unique_together.
unique_together may be deprecated in the future.

For example:

class Volume(models.Model):    id = models.AutoField(primary_key=True)    journal_id = models.ForeignKey(Journals, db_column='jid', null=True, verbose_name="Journal")    volume_number = models.CharField('Volume Number', max_length=100)    comments = models.TextField('Comments', max_length=4000, blank=True)    class Meta:        constraints = [            models.UniqueConstraint(fields=['journal_id', 'volume_number'], name='name of constraint')        ]