I want the instances of a model to be unique

Hello everyone. I 'm really new in django. So i want the instances of my django model to be unique. Here’s my models.

class Department(models.Model):
      name = models.CharField(max_length=200)
      shortcode = models.CharField(max_length=20, unique=True)

      def __str__(self):
            return self.name

class ExamSystem(models.Model):
    department = models.ForeignKey(Department,to_field='shortcode', on_delete=models.CASCADE, related_name='department')
    semester = models.CharField(max_length=10)
    year = models.CharField(max_length=10)

     def __str__(self):
        return self.department.shortcode+' '+self.exam_system.year+' year '+ self.semester + ' sem'

In the exam system model, I want to create instances like 1st year 1st sem, 1st year 2nd sem etc. but the thing is I don’t want to create 1st year 1st sem multiple times because it’s possible to create like this. how to check if the instance with the exact same values have been created and if the instance already exist, how to show error message and prevent it from being created.
Thanks in advance. please help

1 Like

Hey I have solved this problem using unique_together in class meta. :slight_smile: