为 ModelChoiceField 独立于 __str__ 返回多个值

Returning multiple values independently from __str__ for ModelChoiceField

我有 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 admin 中为 FoodCategory 填充了一些值 site.And 我需要将这些值显示为下拉字段,即类别的下拉字段,内容的另一个下拉字段以及类似的准备和时间。

我的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__ 的 return 值上。我怎样才能 return 他们单独?

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

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',)