Django - 将查询集添加到 FilterSet 上的字段时出现问题

Django - Problem adding a queryset to a field on a FilterSet

我有一些 filtersSets 工作正常,但现在我尝试将查询集添加到 FilterSet 上的字段,但在我加载页面时它失败了。

我将 Django 2.1.1 与 Python 3.6 和 Django-filter 2.0.0 一起使用。

查看

def search_jobs(request):
    job_list = Job.objects.filter(project__status="P", is_deleted="False")
    job_filter = JobsListFilter(request.GET, queryset=job_list)
    return render(request, 'webplatform/jobs_list_filter.html', {'filter': job_filter})

过滤器

class JobsListFilter(django_filters.FilterSet):

    # LINE ADDED - the following line is the added queryset 
    projects = Project.objects.filter(status="P", is_deleted="False") 

    skills = WorkerSkills.objects.filter(
        id__in=Job.objects.values_list('required_skills__id', flat=True).distinct())

    worker_job = django_filters.CharFilter(method='my_filter')
    required_skills = django_filters.ModelMultipleChoiceFilter(queryset=skills, widget=forms.SelectMultiple)

    # LINE ADDED - The following line is the one that adds the queryset inside the field I want to filter.
    project = django_filters.ChoiceFilter(queryset=projects)

    compensation_type = django_filters.ChoiceFilter(choices=Job.COMPENSATION_TYPE, widget=forms.RadioSelect)

    class Meta:
        model = Job
        fields = ['worker_job', 'required_skills', 'project', 'compensation_type']

    def my_filter(self, queryset, worker_job, value):
        return queryset.filter(
            worker_job__icontains=value
        ) | queryset.filter(
            work_description__icontains=value
        )

代码在没有在 FilterSet 上添加行 LINE ADDED 的情况下工作。但问题是,在现场 project 它只是让我 select 在所有创建的项目之间,我只想拥有真正必要的项目(在代码上应用查询集)。

但是在代码中添加这些行,当我使用调试模式时,我可以看到应用于字段 project 的查询集给出了预期的结果。但是,在视图的 return 上抛出以下错误。

TypeError at /platform/search/jobs/ __init__() got an unexpected keyword argument 'queryset'

所以我不知道我做错了什么,因为我使用的是在 required_skills 字段上使用的相同结构,添加了一个只包含我想要的对象的查询集,它应该可以工作。

正如@Moisés Hiraldo 在评论中所说,问题是我不得不在 django_filters.ChoiceFilter.

前面使用 django_filters.ModelChoiceFilter