Python Django:此函数的关键字参数无效

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12764347/
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-18 11:49:54  来源:igfitidea点击:

Django: invalid keyword argument for this function

pythondjango

提问by Jurudocs

I want to insert some data into a many to many field. I 'm getting this Error

我想将一些数据插入到多对多字段中。我收到此错误

user is an invalid keyword argument for this function

user 是此函数的无效关键字参数

i also tried it with the relatedName...but still is not working...

我也用 relatedName 尝试过......但仍然无法正常工作......

My model looks like this:

我的模型看起来像这样:

models.py

模型.py

class Workspace(models.Model):
    user = models.ManyToManyField(User,null=False, blank=False, related_name='members')
    workspace_name = models.CharField(max_length=80, null=False, blank=False)
    workspace_cat =models.CharField(max_length=80, null=True, blank=True)

views.py

视图.py

db= Workspace(user=5, workspace_name=data_to_db['workspace_name'],workspace_cat=data_to_db['workspace_category'])
db.save()

Does somebody has an idea? Thanks a lot!

有人有想法吗?非常感谢!

采纳答案by Thomas Orozco

You used a ManyToManyfield for the userfield of your Workspaceobject, you can't give it one user, that's not how a ManyToManyworks, that would be a ForeignKey.

ManyToMany为对象的user字段使用了一个字段Workspace,您不能给它一个用户,这不是 a 的ManyToMany工作方式,那将是ForeignKey.

Basically, using a ForeignKey, each workspace has one Userassociated to it, there's a direct link Workspace -> User, so it makes sense to create a Workspaceand pass it an User, like you would be filling in a CharField.

基本上,使用 a ForeignKey,每个工作区都有一个User与之关联,有一个直接链接Workspace -> User,因此创建 aWorkspace并将其传递给 an是有意义的User,就像您填写CharField.

A ManyToManyrelationship means that several users can be associated to a Workspaceand several Workspacesto one User. When using a ManyToMany, you would create your Workspaceand thenadd some Users to it.

ManyToMany关系意味着几个用户可以关联到一个Workspace和几个Workspaces到一个User。使用 a 时ManyToMany,您将创建您的Workspace然后向其中添加一些Users。

To add to a ManyToManyrelationship, do the following:

要添加到ManyToMany关系,请执行以下操作:

my_user = User.objects.get(pk = 5)
my_workspace = Workspace(workspace_name=data_to_db['workspace_name'],workspace_cat=data_to_db['workspace_category'])
my_workspace.save() # committing to the DB first is necessary for M2M (Jurudocs edit)
my_workspace.users.add(my_user)

You should rename the userfield to usersto make the relationship name clearer.

应该将该user字段重命名为users以使关系名称更清晰。