How to post foreign key id only once in Django

Issue

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 !!

Solution

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/

Answered By – Amrit Bera

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published