【问题标题】:Returning multiple values independently from __str__ for ModelChoiceField独立于 __str__ 为 ModelChoiceField 返回多个值
【发布时间】:2016-01-16 15:58:49
【问题描述】:

我有 models.py 为:

class FoodCategory(models.Model):
    category = models.CharField(max_length = 50)
    content = models.CharField(max_length= 50, null = True,blank=True)
    preparation = models.CharField(max_length= 50, null=True, blank=True)
    time = models.CharField(max_length=50,null=True, blank=True)
    def __str__(self):
        return '%s %s %s %s' % (self.category, self.content, self.preparation, self.time)

现在我从 django 管理站点为 FoodCategory 填写了一些值。我需要将这些值显示为下拉字段,即类别的下拉字段、内容的另一个下拉字段以及准备和时间的类似下拉字段。

我的forms.py如下:

class FoodForm(forms.ModelForm):
    category = forms.ModelChoiceField(queryset=Category.objects.all())
    time = forms.ModelChoiceField(queryset=Category.objects.all())
    preparation = forms.ModelChoiceField(queryset=Category.objects.all())
    content = forms.ModelChoiceField(queryset=Category.objects.all())
    class Meta:
        model = FoodItems
        fields = ('name','time', 'category', 'content', 'preparation', 'comment',)

但现在所有下拉字段都显示为:

我需要将 Starter-Soup、Veg、American、Breakfast 分别分类、内容、准备、时间

所以我认为问题在于__str__ 的返回值。如何单独退货?

【问题讨论】:

    标签: python django django-forms


    【解决方案1】:

    您可以通过创建自定义模型选择字段来实现此目的:

    class CategoryModelChoiceField(ModelChoiceField):
        def label_from_instance(self, obj):
            return obj.category
    
    class TimeModelChoiceField(ModelChoiceField):
        def label_from_instance(self, obj):
            return obj.time
    
    class PreparationModelChoiceField(ModelChoiceField):
        def label_from_instance(self, obj):
            return obj.preparation
    
    class ContentModelChoiceField(ModelChoiceField):
        def label_from_instance(self, obj):
            return obj.content
    

    forms.py:

    class FoodForm(forms.ModelForm):
        category = CategoryModelChoiceField(queryset=Category.objects.all())
        time = TimeModelChoiceField(queryset=Category.objects.all())
        preparation = PreparationModelChoiceField(queryset=Category.objects.all())
        content = ContentModelChoiceField(queryset=Category.objects.all())
        class Meta:
            model = FoodItems
            fields = ('name','time', 'category', 'content', 'preparation', 'comment',)
    

    【讨论】:

    • 好的,谢谢!这行得通.. 但是方法label_from_instance(self, obj) 是如何被调用的?我对 python 和 django 比较陌生
    • 将调用模型的 str(Python 2 上的 unicode)方法来生成对象的字符串表示形式,以用于字段的选择;提供自定义表示,子类 ModelChoiceField 并覆盖 label_from_instance。此方法将接收模型对象,并应返回适合表示它的字符串。欲了解更多信息,请阅读docs.djangoproject.com/es/1.9/ref/forms/fields
    • 还有另一个选项可用于指定要用作字段小部件“to_field_name”中选项值的字段
    • 我遇到了问题。现在,当我保存选择字段值时,它会作为一个整体保存,例如:Starter_soup Veg American Breakfast 用于每个列类别、内容、准备、时间
    猜你喜欢
    • 2018-05-18
    • 1970-01-01
    • 2014-08-11
    • 2020-02-07
    • 1970-01-01
    • 1970-01-01
    • 2015-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多