过滤数据并按否定显示结果。的帖子

时间:2013-04-23 04:49:42

标签: python django python-2.7

在Django中,我需要过滤数据并显示结果。例如

Company3(20)
Company1(12)
Company2(3)

此处“Company1,Company2,Company3”是公司名称,括号内的“20,12,3”为否。特定公司发布的职位。

models.py

class User(models.Model):
     first_name= forms.CharField(max_length=30,widget=forms.TextInput())
     last_name = forms.CharField(max_length=30,widget=forms.TextInput())
     username = forms.CharField(max_length=30,widget=forms.TextInput())
     email = forms.EmailField(widget=forms.TextInput())
     password = forms.CharField(widget=forms.PasswordInput())
     companyname = forms.CharField(max_length=30,widget=forms.TextInput())

class jobs(models.Model):
     emp = models.ForeignKey(User, unique=False)
     title = models.CharField(max_length=30)
     referencecode = models.CharField(max_length=30)
     jobsummary = models.TextField()
     jobdetails = models.TextField()
     key_skills = models.CharField(max_length=30)

我试图给views.py就像

def search_result(request):

     details=User.objects.filter(jobs__isnull=False).select_related()
     return render_to_response('searchresult.html', {'details': details})

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

提供一些想法以显示结果,如上所述

3 个答案:

答案 0 :(得分:1)

您应该使用d1.jobs_set.count来获取工作计数。

因此,请将模板更新为:

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

答案 1 :(得分:1)

或许更高效看起来像

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

然后在模板中

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

答案 2 :(得分:0)

你真的应该拥有Company模型;在aggregation api的帮助下,这将使这项工作变得简单;但是对于你的情况,你需要在你看来这样做:

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})

您的模板将成为:

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