[Answered ]-Filter the data and display result ordered by no. of post

1👍

perhaps a more efficient would look like

details = User.objects.filter(jobs__isnull=False).annotate(job_count=Count('jobs'))\
                   .order_by('job_count')

and then in the template

<ul>
{% for d1 in details %}
    <li>{{ d1.companyname }}({{ d1.job_count }})</li>
{% endfor %}
</ul>
👤Al W

1👍

You should use d1.jobs_set.count instead, to get the count of jobs.

So update your template to:

<ul>
{% for d1 in details %}
    <li>{{ d1.companyname }}({{ d1.jobs_set.count }})</li>
{% endfor %}
</ul>
👤Rohan

0👍

You really should have a Company model; which would have made this a simple task with the help of the aggregation api; but for your case you’ll need to do it in your view:

from collections import defaultdict

from django.shortcuts import render

def search_result(request):

    company_count = defaultdict(int)
    for obj in User.objects.filter(jobs__isnull=False).select_related():
        company_count[obj.companyname] += 1

    return render(request, 'searchresult.html', {'details': company_count})

Your template would become:

{% for company_name in details %}
    {{ company_name }}({{ details.company_name }})
{% endfor %}

Leave a comment