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

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`

最佳答案

您的模型类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'}
]


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

08-06 00:09