1

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

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

这里“Company1,Company2,Company3”是公司名称,括号内的“20,12,3”是no。特定公司发布的职位。

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>

给出一些想法来显示结果,如上所示

4

3 回答 3

1

您应该改为使用d1.jobs_set.count来获取作业数。

因此,将您的模板更新为:

<ul>
{% for d1 in details %}
    <li>{{ d1.companyname }}({{ d1.jobs_set.count }})</li>
{% endfor %}
</ul>
于 2013-04-23T05:07:54.483 回答
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>
于 2013-04-23T05:20:58.043 回答
0

你真的应该有一个Company模型;在聚合 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 %}
于 2013-04-23T05:08:55.487 回答