Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/24.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/solr/3.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
Python 加上一句「;“空的”;基于模型数据选择字段的选项_Python_Django_Forms_Choicefield - Fatal编程技术网

Python 加上一句「;“空的”;基于模型数据选择字段的选项

Python 加上一句「;“空的”;基于模型数据选择字段的选项,python,django,forms,choicefield,Python,Django,Forms,Choicefield,我正在根据模型的数据定义一个ChoiceField field = forms.ChoiceField(choices=[[r.id, r.name] for r in Model.objects.all()]) 但是,我想在我的选项前面加一个空选项来选择“否”对象。 但我找不到一个好的方法来准备 我所有的测试都像: field = forms.ChoiceField(choices=[[0, '----------']].extend([[r.id, r.name] for r in Mod

我正在根据模型的数据定义一个ChoiceField

field = forms.ChoiceField(choices=[[r.id, r.name] for r in Model.objects.all()])
但是,我想在我的选项前面加一个空选项来选择“否”对象。 但我找不到一个好的方法来准备

我所有的测试都像:

field = forms.ChoiceField(choices=[[0, '----------']].extend([[r.id, r.name] for r in Model.objects.all()]))
返回“非类型对象不可编辑”错误。 到目前为止,我找到的唯一方法是:

def append_empty(choices):
    ret = [[0, '----------']]
    for c in choices:
        ret.append(c)
   return ret
当我定义我的领域时:

forms.ChoiceField(choices=append_empty([[r.id, r.name] for r in
    Restaurant.objects.all()]), required=False)
然而,我希望保持我的代码干净,不要有那种恐怖。 你能给我一个主意吗P
提前感谢。

一个简单的答案是:

field = forms.ChoiceField(choices=[[0, '----------']] + [[r.id, r.name] for r in Model.objects.all()])
不幸的是,你的方法有缺陷。即使使用“工作”方法,字段选项也是在定义表单时定义的,而不是在实例化表单时定义的——因此,如果将元素添加到模型表中,它们将不会出现在选项列表中

您可以通过在表单的
\uuuu init\uuu
方法中进行分配来避免这种情况


然而,有一种更简单的方法。与其动态地处理字段选择,不如使用专门设计用于提供模型选项的字段-
modelcooicefield
。这不仅可以在实例化时动态地获取模型元素列表,而且默认情况下还包括一个空白选项。请参阅。

因为这个问题及其答案几乎解决了我刚才遇到的一个问题,所以我想补充一点。对我来说,id必须为空,因为模型没有将“0”识别为有效选项,但它接受为空(null=True,blank=True)。在初始值设定项中:

self.fields['option_field'].choices = [
    ('', '------')] + [[r.id, r.name] for r in Model.objects.all()]