使用字典在模型中创建对象时的Django TypeError

时间:2017-05-16 07:56:05

标签: python django dictionary django-models

我试图将字典中的项目传递给模型,每个键,值对都是一个对象。

d1 = {'Alex': 3.0, 'Chriss': 7.42, 'Robert': 9.13}

这是模型:

class Team_one(models.Model):
    name = models.CharField(max_length=100)
    score = models.FloatField(default=0.0)

当我试图在shell中做一个示例时,我遇到了类型错误

这是一个例子:

x = {'Alex': 3.0}
Team_one.objects.create(**x)

m = Team_one(**x)
m.save()

这是错误:

`TypeError: 'Alex' is an invalid keyword argument for this function`

4 个答案:

答案 0 :(得分:2)

是的,你肯定得到一个TypeError,因为你只是为你的值使用字典。字典表示键值存储,因此在您的情况下,您必须指定键及其值:

{
    'name': 'Alex',
    'score': 3.0,
}

如果要创建多个对象,可以只使用for循环:

team_ones = [{'name': 'Alex', 'score': 3.0}, {'name': 'Chriss', 'score': 7.42}, {'name': 'Robert', 'score': 9.13}]

for team_one in team_ones:
    Team_one.objects.create(**team_one)

答案 1 :(得分:2)

这应该有效:

for key, value in d1.items():
    Time_team.objects.create(name=key, score=value)

它使用您的初始d1词典。

答案 2 :(得分:2)

<强> TL:DR

您应该更改字典以匹配您的模型:

x = {
   'name': 'Alex',
   'score': 3.0
}
Team_one.objects.create(**x)

<小时/> 的说明

创建django对象时,create函数需要与模型匹配的**kwargs。在您的情况下,对create()的正确调用将是:

Team_one.objects.create(name='Alex', score=3.0)

当您&#34;解压缩&#34; 您的词典(**x)时,会发生的是密钥作为参数的名称和值传递作为参数值。你最初做了什么,导致对create()错误调用:

Team_one.objects.create(Alex=3.0)

因此,通过将字典更改为以下形式,您可以&#34;解包&#34;它在create()函数中正确显示:

arguments = {
    'name': 'a_name',
    'score': 2.0
}

由于评论而编辑:

你应该做的是:

  1. 更改函数返回词典的方式
  2. 或者改革您收到的字典以匹配上述
  3. 或者拨打create(),不要打开&#34;解压缩&#34;任何东西:

    for item in d1.keys():
        Team_one.objects.create(name=item, score=d1[item])
    

答案 3 :(得分:2)

您的模型类Team_one没有属性Alex

在词典中,您需要键namescore,其值为 Alex 3.0

最终,您可以将检索到的词典转换为词典列表:

team_one = [{'name': name, 'score': score} for name, score in d1.items()]

这是你得到的输出:

[
    {'score': 7.42, 'name': 'Chriss'},
    {'score': 3.0, 'name': 'Alex'},
    {'score': 9.13, 'name': 'Robert'}
]

现在,您可以遍历列表并创建对象。