Python 姜戈错误。不能分配必须是一个实例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37839867/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 20:00:17  来源:igfitidea点击:

Django error. Cannot assign must be an instance

pythondjangomodelforeign-keys

提问by rahimbah

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

当我尝试在我的一个表中运行插入时出现以下错误。

Cannot assign "1": "Team.department_id" must be a "Department" instance

无法分配“1”:“Team.department_id”必须是“Department”实例

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.

诚然,我有点不确定我是否正确使用了外键概念。下面给出了我尝试运行的插入和来自我的 models.py 的片段。

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.

我想做的是当有人想要创建一个新团队时。他们必须将它附加到一个部门。因此部门 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

模型.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)

回答by Anonymous

You don't need to pass the department id, the instance itself is enough. The following should work just fine:

您不需要传递部门 ID,实例本身就足够了。以下应该可以正常工作:

new_team = Team(
    nickname = team_name,
    employee_id = employee_id,
    department_id = Department.objects.get(password = password, department_name = department_name)
)

Just a note, don't ever name your foreign fields something_id. That somethingis enough. Django is meant to make things easy from the user's perspective and the _idsuffix means you're thinking of the database layer. In fact, if you named your column department, django will automatically create department_idcolumn in the database for you. The way things are, you're making django create department_id_idwhich is rather silly.

只是注意,不要老是命名洋田东西_id。那东西就够了。从用户的角度来看,Django 旨在使事情变得简单,_id后缀意味着您正在考虑数据库层。事实上,如果你给你的 column 命名department,django 会自动department_id为你在数据库中创建column 。事情就是这样,你让 django createdepartment_id_id这是相当愚蠢的。