我有两个模型如下:
class Types_of_Expenditures(models.Model):
Expenditure_owner = models.CharField(default="None",max_length=50)
Expenditure_Type = models.CharField(default="Miscellaneous",max_length=50)
Expenditure_Type_Description = models.CharField(max_length=200)
def __unicode__(self):
return self.Expenditure_Type
class Expenditure(models.Model):
exp_owner= models.CharField(default='None',max_length=50)
exp_date = models.DateTimeField("Expenditure_Date")
description = models.CharField(max_length=1000)
amount = models.FloatField(default=0)
currency = models.CharField(max_length=15,default="MYR",editable=True)
exp_pocket = models.ForeignKey(Pockets, null=True, blank=True)
exp_type = models.ForeignKey(Types_of_Expenditures)
class Meta:
unique_together = ('exp_date', 'description',)
def __unicode__(self):
return self.description
对于以上2种型号,我使用以下2种形式:
class Types_of_Expenditures_Form(forms.ModelForm):
class Meta:
model = Types_of_Expenditures
class ExpenditureDeleteForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(ExpenditureDeleteForm, self).__init__(*args, **kwargs)
self.fields['exp_pocket'].widget = forms.TextInput(attrs={'readonly':'readonly'})
self.fields['exp_type'].widget = forms.TextInput(attrs={'readonly':'readonly'})
self.fields['amount'].widget = forms.TextInput(attrs={'readonly':'readonly'})
for f in self.fields:
self.fields[f].widget.attrs['readonly'] = "readonly"
class Meta:
model = Expenditure
exclude = ['exp_owner','currency']
fields = ['exp_date', 'description', 'exp_type', 'amount','exp_pocket']
在我看来,我称之为:
ExpDeleteFormSet = modelformset_factory(Expenditure,extra=0,
can_delete=True,fields = ['exp_date', 'description', 'exp_type', 'amount','exp_pocket'],form=ExpenditureDeleteForm)
formset = ExpDeleteFormSet(queryset=Expenditure.objects.filter(exp_owner=str(request.user)))
return render_to_response('expenditure.html', {'formset':formset}, context)
现在呈现的formset如下图所示:
问题/问题: 正如您在图像中看到的那样,Type被编号为1或2。这个1在Types_of_Expenditure中具有相应的值Miscellaneous,而2具有其他内容,依此类推。 是否可以将类型显示为Types_of_Expenditure的相应值?
我尝试过各种各样的事情,例如使用Baseformset尝试使用查询集但无法找到如何操作?
尝试了什么
使用如下的inlineformset_factory,但这样做会在模板中呈现任何内容:
ExpDeleteFormSet = inlineformset_factory(Types_of_Expenditures,
Expenditure, fk_name="exp_type",
fields = ['exp_date', 'description', 'exp_type', 'amount','exp_pocket'],
can_delete=True,form=ExpenditureDeleteForm)
替代方案效果很好: 我现在使用的另一种方法是将Expenditure_Type本身作为主键,但是我会寻找原始问题的答案:
Expenditure_Type = models.CharField(primary_key=True,max_length=50)