当我尝试向我的一个表中插入数据时,出现了以下错误:
无法分配“1”:“Team.department_id”必须是“Department”的实例
我有点不确定自己是否正确使用了外键概念。下面给出了我尝试运行的插入以及models.py文件中的代码片段。
我想要做的是,当有人想要创建一个新团队时,他们必须将其附加到一个部门。因此,部门ID应该在两个表中都存在。
new_team = Team(
nickname = team_name,
employee_id = employee_id,
department_id = int(Department.objects.get(
password = password,
department_name = department_name
).department_id))
models.py
class Department(models.Model):
department_id = models.AutoField(auto_created=True,
primary_key=True,
default=1)
department_name = models.CharField(max_length=60)
head_id = models.CharField(max_length=30)
password = models.CharField(max_length=128)
class Team(models.Model):
team_id = models.AutoField(primary_key=True)
department_id = models.ForeignKey('Department',
related_name = 'Department_id')
employee_id = models.CharField(max_length=30)
nickname = models.CharField(max_length=60)
team_image = models.ImageField(upload_to=get_image_path,
blank=True, null=True)
new_team.save()
- Karam Qusai