Django优化大数据过滤的代码

时间:2012-01-24 10:54:57

标签: django django-queryset django-cache

当我搜索 15000个结果时,有什么方法可以优化处理速度?

在我的视图中,我正在过滤搜索:

if form.is_valid():

      results = Screening.objects.filter(
         screening_date__range(form.cleaned_data['start_date'],form.cleaned_data['end_date']))

      if form.cleaned_data['company']:
          results = results.filter(company=form.cleaned_data['company'])
      if form.cleaned_data['company_job']:
          results = results.filter(company_job__in=form.cleaned_data['company_job'])
      if form.cleaned_data['company_job_type']:
          results = results.filter(company_job_type=form.cleaned_data['company_job_type'])
      if form.cleaned_data['reason']:
          results = results.filter(reason_for_testing__in=form.cleaned_data['reason'])`

在TEMPLATE中,传递的结果用作:

{% for result in results %}

      <td>{{ result.company.name}}</td>
      <td>{{ result.first_name }} {{ result.last_name }}</td>
      <td>{{ result.company_job.job_number }}</td>
      <td>{{ result.id }}</td>
      <td>{{ result.screening_date|date}}</td></tr>

有没有办法优化处理,还是应该在这种情况下使用缓存或某事?

1 个答案:

答案 0 :(得分:0)

这不是一个答案,只是提示您的代码更易于阅读和使用:

  filters = {
      'screening_date__range': (form.cleaned_data['start_date'],form.cleaned_data['end_date'])
  }

  if form.cleaned_data['company']:
      filters['company'] = form.cleaned_data['company']
  if form.cleaned_data['company_job']:
      filters['company_job__in'] = form.cleaned_data['company_job']
  if form.cleaned_data['company_job_type']:
      filters['company_job_type'] = form.cleaned_data['company_job_type']
  if form.cleaned_data['reason']:
      filters['reason_for_testing__in'] = form.cleaned_data['reason']

  Screening.objects.filter(**filters)