Skip to main content
 首页 » 编程设计

python之使用字典在模型中创建对象时出现 Django TypeError

2025年05月04日23bhlsheji

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

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。

在您的字典中,您需要具有值 Alex 和 3.0 的键 name 和 score。

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

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'} 
] 

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