可以在创建时将字典传递给 Django 模型吗? [英] Can a dictionary be passed to django models on create?
本文介绍了可以在创建时将字典传递给 Django 模型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以用 list
、dictionary
或其他类似的东西来做类似的事情?
Is it possible to do something similar to this with a list
, dictionary
or something else?
data_dict = {
'title' : 'awesome title',
'body' : 'great body of text',
}
Model.objects.create(data_dict)
如果我能扩展它就更好了:
Even better if I can extend it:
Model.objects.create(data_dict, extra='hello', extra2='world')
推荐答案
如果 title
和 body
是模型中的字段,则 您可以使用 ** 运算符提供字典中的关键字参数.
If title
and body
are fields in your model, then you can deliver the keyword arguments in your dictionary using the ** operator.
假设您的模型名为 MyModel
:
# create instance of model
m = MyModel(**data_dict)
# don't forget to save to database!
m.save()
至于你的第二个问题,字典必须是最后的论据.同样,extra
和 extra2
应该是模型中的字段.
As for your second question, the dictionary has to be the final argument. Again, extra
and extra2
should be fields in the model.
m2 =MyModel(extra='hello', extra2='world', **data_dict)
m2.save()
这篇关于可以在创建时将字典传递给 Django 模型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文