How to add new foreign key in my old django models?

I have a model name Employee now i want to add a new fields in this model which will be a foreign key of Department model.I try to solve it the following way but i get error like

django.db.utils.IntegrityError: The row in table 'employee_verification_employee' with primary key 'UP-0319001' has an invalid foreign key: employee_verification_employee.department_id contains a value '03' that does not have a corresponding value in employee_verification_department.id.

class Department(models.Model):
   name = models.CharField(max_length=100)
   id = models.CharField(primary_key=True,max_length=10)

class Employee(models.Model):
   name = models.CharField(max_length=100)
   department = models.CharField(max_length=100,choices = Departments)
   date_of_joining = models.DateField()
   employeed = models.BooleanField(default = True)
   email = models.EmailField(max_length = 254)
   blood_group = models.CharField(max_length=50)
   designation = models.CharField(max_length=100)
   image = models.ImageField(upload_to='employee_images',default = "")
   number = PhoneField(blank=True, help_text='Enter Contact Number')
   emergency_number = PhoneField(blank=True, help_text='Enter Contact Number')
   id = models.CharField(primary_key=True, max_length=200)
   department_new = models.ForeignKey(Department,on_delete=models.CASCADE,blank=True)

   def save(self, *args, **kwargs):
       if not self.id:
           nth_member = Employee.objects.filter(department = self.department).count()+1
           self.id = "UP-" + self.department + self.date_of_joining.strftime("%y")+"{:03d}".format(nth_member)
           print(self.id)
       super(Employee, self).save(*args, **kwargs)
   
   def __str__(self):
       return self.name + "--"+ self.designation``
[![enter image description here][1]][1]


 [1]: https://i.stack.imgur.com/xdRMd.png

As @trigo said, all you need is:

class Department(models.Model):
   name = models.CharField(max_length=100)

class Employee(models.Model):
   name = models.CharField(max_length=100)
   department = models.CharField(max_length=100,choices = Departments)
   date_of_joining = models.DateField()
   employeed = models.BooleanField(default = True)
   email = models.EmailField(max_length = 254)
   blood_group = models.CharField(max_length=50)
   designation = models.CharField(max_length=100)
   image = models.ImageField(upload_to='employee_images',default = "")
   number = PhoneField(blank=True, help_text='Enter Contact Number')
   emergency_number = PhoneField(blank=True, help_text='Enter Contact Number')
   department_new = models.ForeignKey(Department,on_delete=models.CASCADE,blank=True)

And Django will take care of the rest (ids).

Back to Top