Django模型错误 - "TypeError: 'xxx'是此函数的无效关键字参数

9 投票
1 回答
8517 浏览
提问于 2025-04-17 09:15

我遇到了这个错误:

TypeError: 'person' is an invalid keyword argument for this function

我的模型是:

class Investment(models.Model):
company = models.ManyToManyField("Company", related_name ="Investments_company")
financial_org = models.ManyToManyField("Financial_org", related_name ="Investments_financial_org")
person = models.ManyToManyField("Person", related_name ="Investments_person")

我的测试(导致错误的测试):

investment1 = Investment(company = [], financial_org = financial1, person = [])

1 个回答

26
  1. 先创建你的模型,不要涉及多对多关系,比如你可以写 investment1 = Investment() 来实例化一个投资模型。

  2. 保存你的模型,可以用 investment1.save() 来把它保存到数据库里。

  3. 添加多对多关系,有几种方法可以做到,比如你可以用 investment1.person.add(person_model) 来添加一个人,或者用 investment1.person.create(name='foo') 来创建一个新的人。

在模型保存之前,你不能使用多对多关系,这是因为多对多关系表中的一行需要两个模型的主键(pk),也就是它们的唯一标识符。

撰写回答