Django错误.无法分配必须是实例 [英] Django error. Cannot assign must be an instance
问题描述
当我尝试在我的一个表中运行插入时,出现以下错误.
I get the following error when I try to run an insert into one of my tables.
无法分配"1":"Team.department_id"必须是部门"实例
Cannot assign "1": "Team.department_id" must be a "Department" instance
诚然,我不确定我是否正确使用了外键概念.我正在尝试运行的插入和来自我的models.py的片段在下面给出.
Admittedly I'm slightly unsure if I'm using the foreign key concept correctly. The insert I'm trying to run and a snippet from my models.py are given below.
我想做的是有人要创建新团队时.他们必须将其附加到部门.因此,部门ID应该在两组表中.
What I'm trying to do is that when someone wants to create a new team. They have to attach it to a department. Therefore the department ID should be in both sets of tables.
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
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)
推荐答案
您无需传递部门ID,实例本身就足够了.以下应该可以正常工作:
You don't need to pass the department id, the instance itself is enough. The following should work just fine:
new_team = Team(
nickname = team_name,
employee_id = employee_id,
department_id = Department.objects.get(password = password, department_name = department_name)
)
仅需注意,请勿将您的外国字段命名为 _id. 某事就足够了. Django旨在从用户角度简化事情,后缀_id
表示您正在考虑数据库层.实际上,如果您将列命名为department
,则django会自动在数据库中为您创建department_id
列.事情就是这样,您正在让django创建department_id_id
,这很愚蠢.
Just a note, don't ever name your foreign fields something_id. That something is enough. Django is meant to make things easy from the user's perspective and the _id
suffix means you're thinking of the database layer. In fact, if you named your column department
, django will automatically create department_id
column in the database for you. The way things are, you're making django create department_id_id
which is rather silly.
这篇关于Django错误.无法分配必须是实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!