我将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__
的返回值。我怎样才能单独归还?
答案 0 :(得分:2)
您可以通过创建自定义模型选择字段来实现此目的:
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',)