我正在开展一个小型项目,其中发布的职业将被排名。排名取决于职位发布的次数。我设法查询数据并对职业进行排名。但是在模板中,当我尝试显示职业及其百分比时,只显示他们的“id”。我希望看到占领的名字。以下是流量 #models.py
class OccupationGroup(models.Model):
group=models.CharField(max_length=200)
def __str__(self):
return self.group
class Occupation(models.Model):
group=models.ForeignKey(OccupationGroup)
occupation=models.CharField(max_length=200)
def __str__(self):
return self.occupation
class OccupationData(models.Model):
group=models.ForeignKey(OccupationGroup) #added for testing
occupation=ChainedForeignKey(Occupation,chained_field='group', chained_model_field='group',)#added for testing
county=models.CharField(max_length=600)
date_of_advertisement=models.DateField(verbose_name="Date of Adveertisement")
#source=models.CharField(max_length=200,null=True, blank=True, verbose_name="Source")
positions=models.CharField(max_length=200, verbose_name="Number of positions")
def __str__(self):
return self.occupation
def view(request):
context_dict={}
total_items = OccupationData.objects.count()
items = [
{'data': g['occupation'], 'value': g['total'] * 100 / total_items} for g in data
]
context_dict={'data':items}
return render(request,'template.html',context_dict)
{% for data in data %}
{{data.data }}
{{ data.value|floatformat:"2" }}%<br>
{% endfor %}
1 23%
2 21.22%
3 11.12%
Chemists 23%
Lawyers 21.22%
Mathematicians 11.12%
我得到这项工作的权利是什么?
答案 0 :(得分:0)
我终于明白了。我了解到value()
并不识别任何数据库关系。它选择指定字段中的确切值。因此,建议在将视图传递给模板之前获取视图中的所有值。
下面的代码解决了问题
def view(request):
context_dict={}
total_items = OccupationData.objects.count()
data=DemandData.objects.values('occupation','occupation__occupation').annotate(total=Count('occupation')).order_by('-total')
items = [
{'data': g['occupation__occupation'], 'value': g['total'] * 100 / total_items} for g in data
]
context_dict={'data':items}
return render(request,'template.html',context_dict)