Django在模板中注释

时间:2016-10-15 18:39:06

标签: python django annotate

我正在开展一个小型项目,其中发布的职业将被排名。排名取决于职位发布的次数。我设法查询数据并对职业进行排名。但是在模板中,当我尝试显示职业及其百分比时,只显示他们的“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

views.py

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)

template.html

{% 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%

我得到这项工作的权利是什么?

1 个答案:

答案 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)