使用带有Foreignkey的django模型如下:
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
现在我在我正在做的支出类型中保存数据:
Types_of_Expenditures.objects.get_or_create(Expenditure_owner='a',Expenditure_Type_Description="Default one")
,数据库数据如下:
id Expenditure_owner Expenditure_Type Expenditure_type_description
1 a Miscellaneous default one
但是当我向支出数据添加任何内容时,exp_type中的数据保存为1,但它应该是杂项,因为在def unicode 中我将返回Expenditure_type。
以下是我如何使用formset保存支出模型的数据:
ExpFormSet = modelformset_factory(Expenditure,extra=10,max_num=10,
fields=('exp_date', 'description','exp_type','amount','currency','exp_pocket'),
can_delete=False,form=ExpenditureForm)
if request.method == 'POST':
formset = ExpFormSet(request.POST,queryset=Expenditure.objects.filter(exp_owner=request.user))
if formset.is_valid():
print "printing formset",formset
formset.save(commit=True)
cd = form.cleaned_data
expenditureType = cd.get('exp_type')
print "Expenditure Type entered is ",expenditureType
return index(request)
我在索引视图中正在做什么:
Expenditure_list = Expenditure.objects.order_by('-exp_date').filter(exp_owner=request.user)
print "Expenditure List is : ", Expenditure_list.values_list()
现在,此支出视图的输出为Expenditure_list.values_list()的值为(请参阅上一个值,即1,即exp_type的值):
Expenditure List is : [(3, u'a', datetime.datetime(2014, 9, 12, 15, 32, 10), u'test', 1.0, u'MYR', u'pocket', 1)]
我的期望是什么:
Expenditure List is : [(3, u'a', datetime.datetime(2014, 9, 12, 15, 32, 10), u'test', 1.0, u'MYR', u'pocket', u'Miscellaneous')]
任何人都可以帮助解决这里的问题吗?
我觉得这个问题可能是错的,可能只会保存外键,即id,为了获得支出类型,我需要使用Types_of_Expenditure.objects.get检索它(pk =" Key in list& #34)
但不确定是否有替代方法?
答案 0 :(得分:1)
我想我理解你的问题。您似乎期望values_list
返回相关模型的__unicode__
,但没有理由认为它:顾名思义,它会返回值 only,而ForeignKey字段的值只是ID。
如果您愿意,可以向values_list
提供一个字段名列表并遍历那里的关系:
Expenditure.objects.values_list('description', 'amount', 'exp_type__ Expenditure_Type')