![](/img/trans.png)
[英]Returning multiple values independently from django model for modelchoicefield
[英]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管理站點中填寫了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__
的返回值。 如何單獨退還?
您可以通過創建自定義modelchoice字段來實現:
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
form.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',)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.