ORM过滤器没有结果

时间:2017-02-18 12:57:52

标签: django forms view filter orm

我有一个观点:

def PeopleView(request):
    ...
    parameters = copy.deepcopy(request.GET)
    for parameter in request.GET:
        if not request.GET.get(parameter):
            del parameters[parameter]
    people = Person.objects.filter(**parameters)
    search_form = PersonSearchForm()
    return render(request, 'persons/people.html', {
        'people': people,
        'search_form': search_form,
        ...
    })

PersonSearchForm:

class PersonSearchForm(forms.Form):
    first_name = forms.CharField(required=False)
    last_name = forms.CharField(required=False)
    second_name = forms.CharField(required=False)
    country = forms.CharField(required=False)
    city = forms.CharField(required=False)
    gender = forms.CharField(widget=forms.Select, required=False)
    birthday = forms.DateField(required=False)
    school = forms.CharField(required=False)
    university = forms.CharField(required=False)
    profession = forms.CharField(required=False)

Person模型具有PersonSearchForm中具有相同名称的字段。此表单由用户作为GET请求发送。

GET请求和打印参数变量: enter image description here

但是过滤器始终没有结果。怎么了?

1 个答案:

答案 0 :(得分:1)

<强>解

我解决了这个问题。解决方案是将querydict参数转换为dict对象。它看起来像:

...
filter_parameters = {}
for parameter in parameters:
    filter_parameters[parameter] = parameters[parameter]
people = Person.objects.filter(**filter_parameters)
...

它有效。