可以将字典传递到django模型上创建? [英] Can a dictionary be passed to django models on create?
本文介绍了可以将字典传递到django模型上创建?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
data_dict = {
'title':'awesome title',
'body':'great body of text',
}
Model.objects.create(data_dict)
更好的,如果我可以扩展它
Model.objects.create(data_dict,extra ='hello',extra2 ='world)
解决方案
如果 title
和 body
是模型中的字段,您可以使用**操作符在您的字典中传递关键字参数a href =http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists =noreferrer>
假设您的模型称为 MyModel
:
#创建模型的实例
m = MyModel(** data_dict)
#不要忘记保存到数据库!
m.save()
至于你的第二个问题,字典必须是最终论证。再次, extra
和 extra2
应该是模型中的字段。
= $ m $($)$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ c>
Is is possible to do something similar to this with a list, dictionary or something else even?
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)
解决方案
If title
and body
are fields in your model, then you can deliver the keyword arguments in your dictionary using the ** operator.
Assuming your model is called MyModel
:
# create instance of model
m = MyModel(**data_dict)
# don't forget to save to database!
m.save()
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屋!
查看全文