0

I am working on a small project in which occupations posted are to be ranked. Ranking is on the basis of the number of times an occupation is posted. I have managed to query the data and rank the occupation. However in the template when I try display the occupations and their percentages, it's only their 'id' which is displayed. I want the occupation's name to appear instead. Below are the flows #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 %}

Sample Output

1 23%
2 21.22%
3 11.12%

Required Output

Chemists 23%
Lawyers 21.22%
Mathematicians 11.12%

What am I not getting right to get this work??

1 Answers1

0

I finally figured it out. I learnt that the value()doesn't recognize any database relation. It picks the exact value in the specified field.It is therefore advisable to get all the values in the views before passing them to the template. the code below solved the problem

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)