Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/ssh/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用一个或多个项创建Django对象(动态)_Django_Dictionary_Django Models - Fatal编程技术网

使用一个或多个项创建Django对象(动态)

使用一个或多个项创建Django对象(动态),django,dictionary,django-models,Django,Dictionary,Django Models,有没有办法使用model.objects.create() 假设我的模型有许多可选字段。我只想传递一个dict,而不是手动分配每个字段,如: Model.objects.create(thing=data['prop'],…) 这里有一个更清晰的(伪代码)示例:假设我有一个 class MyModel(models.Model): thing=models... // all these fields null=True, blank=True another=... possibl

有没有办法使用
model.objects.create()

假设我的模型有许多可选字段。我只想传递一个dict,而不是手动分配每个字段,如:

Model.objects.create(thing=data['prop'],…)

这里有一个更清晰的(伪代码)示例:假设我有一个

class MyModel(models.Model):
  thing=models... // all these fields null=True, blank=True
  another=...
  possibly_another=...
  ...

data = {'thing': 'value for thing', 'another': 'value for another'}

MyModel.objects.create(data)
在本例中,我的
数据
可能没有另一个
或更多。我尝试过这样做,但我得到一个位置arg错误。。。我做了一些谷歌foo,我必须没有我的条款正确。(我更像是一个node/js家伙)

有没有一种方法可以传递dict并让create方法整理出有什么和没有什么?

您可以使用两个连续的星号(
**
)来执行字典解包:

MyModel.objects.create(**数据)
如果字典包含例如
data={'a':4,'b':2}
,如果执行字典解包
f(**data)
,它将使用
f(a=4,b=2)
调用函数


请注意,对于缺少的值,在这些字段中应该有
default=…
参数。

这正是我需要知道的!谢谢你的知识伙伴,当然。已设置默认值。我会尽快记下你的答案。再次感谢。这正是我丢失的语言信息。
MyModel.objects.create(**data)