class Department(models.Model):
name = models.CharField(max_length=50)
class Employee(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
department = models.ForeignKey(
Department,
on_delete=models.CASCADE
)
I'm really wondering how to do this. Suppose there are three departments with id 1, 2, 3. So in employee model if i posted some employee with name abc and department 1. So next time if i will try to post the same department id that is 1 for another employee. I should not be able to do that. Validating this field does not work i believe because of foreign key.So how to achieve this. Any help would be really appreciated. Thank you !!
CodePudding user response:
You are looking for One-to-one relationship. With this, only one combination of department and employee will exist.
department = models.OneToOneField(Department, on_delete=models.CASCADE)
Here’s more info: https://docs.djangoproject.com/en/3.2/topics/db/examples/one_to_one/