简体   繁体   中英

How to post foreign key id only once in Django

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

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM