由queryset填充的Django选择字段 - 保存id但显示值

时间:2015-12-01 07:41:55

标签: django django-models django-forms django-templates

我有两个模型,TagTagGroup

class TagGroup(models.Model):
    tag_group_name = models.CharField(max_length=100)

class Tag(models.Model):
    tag_name = models.CharField(max_length=100)
    tag_group = models.ForeignKey(TagGroup, blank=True, null=True)

我已将TagGroup表单作为选择字段放入模板中,以便我可以为标记分配TagGroup。我创建了此表单以从TagGroup查询集填充。

class TagGroupForm(ModelForm):
    tag_group_name = forms.ModelChoiceField(queryset=TagGroup.objects.values_list('id', 'tag_group_name'), required=False)

    class Meta:
        model = TagGroup
        fields = [
            'tag_group_name'
        ]

我还没有看到任何明显的说明如何将ID分配给Tag表,同时向用户显示模板中选项字段中的Tag值。

目前上面显示:

enter image description here

几个问题:

  1. 查询集是否正确?我没试过" values_list"但它只是显示了一个"对象"在模板中的表单字段中?

  2. 我如何隐藏' Id我可以保存它,同时只向用户显示表单字段中的实际字符串值吗?

  3. 已编辑添加更新的表单:

    class TagGroupForm(ModelForm):
        tag_group_name = forms.ModelChoiceField(queryset=TagGroup.objects.all(), to_field_name = 'tag_group_name', required=False)
    
        class Meta:
            model = TagGroup
            fields = [
                'tag_group_name'
            ]
    

    这现在产生以下..看起来接近..表单值有一个很好的字符串,但显示给用户的实际值仍然是" TagGroup对象"。如何让它显示?

    enter image description here

1 个答案:

答案 0 :(得分:2)

来自the docs

  

将调用模型的 str (Python 2上的 unicode )方法以生成要使用的对象的字符串表示

所以简单地将它分配给对象名称,一切都会好的! (另外,您不需要使用values_list)默认情况下显示Object的原因是因为这是默认字符串表示形式。

class TagGroup(models.Model):
    tag_group_name = models.CharField(max_length=100)

    def __str__(self):
        return self.tag_group_name

tag_group_name = forms.ModelChoiceField(queryset=TagGroup.objects.all(), required=False)

或者,如果您不想修改此内容并希望将其保留用于其他用途。

  

要提供自定义表示,请继承ModelChoiceField并覆盖label_from_instance。此方法将接收模型对象,并应返回适合表示它的字符串

class TagChoiceField(ModelChoiceField):
     queryset = TagGroup.objects.all()
     def label_from_instance(self, obj):
         return obj.tag_group_name  # or similar