Django 错误.不能分配必须是实例

2022-01-20 00:00:00 python django model foreign-keys

问题描述

当我尝试在我的一个表中运行插入时收到以下错误.

I get the following error when I try to run an insert into one of my tables.

不能分配1":Team.department_id"必须是Department"实例

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

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

请注意,永远不要将您的外来字段命名为 something_id.something 就足够了.从用户的角度来看,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.

相关文章