Explore Courses Blog Tutorials Interview Questions
0 votes
in Python by (47.6k points)

Is there a way to define a couple of fields as unique in Django?

I have a table of volumes (of journals) and I don't want more than one volume number for the same journal.

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)

I tried to put unique = True as an attribute in the fields journal_id and volume_number

but it doesn't work.

1 Answer

0 votes
by (106k points)

To define a couple of fields as unique in Django there is a simple solution you just need to call unique_together which defines the fields as unique in Django.

An example that illustrates how we use unique_together:

class MyModel(models.Model):

      field1 = models.CharField(max_length=50)

      field2 = models.CharField(max_length=50)

class Meta:

      unique_together = ('field1', 'field2',)

For your code, you will write unique_together  like as follows:-

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',)

Browse Categories