如何在 Django 中的两个动态搜索表单上使用 Q 对象

How can I use Q objects on Two Dynamic Search Forms in Django

我正在做一个 Django 项目,我想在其中搜索居住在特定国家和州的个人资料记录。

在这个项目中,我将收集来自不同国家和他们各自州的人的数据,所以我想要一种情况,我可以有两个针对国家和州的搜索表单。

表单应该允许我在配置文件模型中列出 select 国家/地区列表,而状态表单应该允许我输入和搜索 selected 国家/地区中的州.

结果应该是 selected 国家/地区的人员列表并进行了搜索 state.Please 了解我决定使用 Q 对象,因为我了解到它可以提高查询效率。

这是我的模型代码:

class Profile(models.Model):
    applicant = models.OneToOneField(User, on_delete=models.CASCADE, null = True)
    surname = models.CharField(max_length=10, null=True)
    othernames = models.CharField(max_length=30, null=True)
    gender = models.CharField(max_length=6, choices=GENDER, blank=True, null=True)
    nation = models.CharField(max_length=10, choices=NATION, blank=True, null=True)
    state = models.CharField(max_length=20, null=True)
    address = models.CharField(max_length=200, null=True)
    phone = models.CharField(max_length=11, null=True)
    image = models.ImageField(default='avatar.jpg', upload_to ='profile_images')

这是我的搜索表单代码:

class Applicant_Search_Form(forms.ModelForm):

class Meta:
    model = Profile
    fields = ['nation', 'state']

这是我的观点代码:

def SearchApplicants(request):

form = Applicant_Search_Form(request.GET or None)

if form:
    list_submited = Q(nation__icontains = form['nation'].value()) & Q(state__icontains = form['state'].value())

else:
    list_submited = Profile.objects.all()

paginator = Paginator(list_submited, 5)
page = request.GET.get('page')
paged_listApps = paginator.get_page(page)

context = {
'list_applicants':paged_listApps,
'form':form,


}

return render(request, 'user/list_applicants.html',context)

我已经尝试 运行 上面的代码但是我有一个 TypeError 说 'Q' object is not subscriptable.

应该有人帮助解决这个问题,并可能是解决这种问题的最佳方法search.Thank,期待您的回答。

您应该过滤 Profile.objects.all() 查询集,因此:

def SearchApplicants(request):
    form = Applicant_Search_Form(request.GET)
    if form<strong>.is_valid()</strong>:
        list_submited = Profile.objects<strong>.filter(</strong>
            nation__icontains=form.cleaned_data['nation'],
            state__icontains=form.cleaned_data['state']
        <strong>)</strong>
    else:
        list_submited = Profile.objects.all()
    # …

Note: Functions are normally written in snake_case, not PascalCase, therefore it is advisable to rename your function to search_applicants, not SearchApplicants.


Note: Forms in Django are written in PascalCase, not snake_case, so you might want to rename the model from Applicant_Search_Form to ApplicantSearchForm.