我想自定义搜索表单的SearchQuerySet以搜索所有可能的结果,例如sql表达式" LIKE",文档说:
SearchForm 最基本的表单类型,此表单由单个字段q字段(用于查询)组成。在搜索时,表单将获取q字段的已清理内容,并在您提供的自定义SearchQuerySet或默认SearchQuerySet上执行auto_query。
要自定义表单将使用的SearchQuerySet,请使用您要使用的SearchQuerySet将searchqueryset参数传递给构造函数。如果将此表单与SearchView结合使用,表单将接收您为视图提供的任何SearchQuerySet,而无需额外的工作。
可以将auto_query更改为icontains搜索吗?
这是我的班级,我必须修改?:
class ContactSearchForm(HighlightedModelSearchForm):
name = forms.CharField(max_length=100,required=False)
surname = forms.CharField(max_length=100,required=False)
work = forms.CharField(max_length=100,required=False)
province = forms.CharField(max_length=100,required=False)
status = forms.CharField(max_length=100,required=False)
sex = forms.CharField(max_length=100,required=False)
city = forms.CharField(max_length=100,required=False)
street = forms.CharField(max_length=100,required=False)
zip = forms.CharField(max_length=100,required=False)
def no_query_found(self):
return self.searchqueryset
def search(self):
sqs = super(ContactSearchForm,self).search()
if not self.is_valid():
return self.no_query_found()
if self.cleaned_data['name']:
sqs = sqs.filter(content__icontains = self.cleaned_data["name"])
if self.cleaned_data['surname']:
sqs = sqs.filter(content__icontains = self.cleaned_data['surname'])
if self.cleaned_data['work']:
sqs = sqs.filter(content__icontains = self.cleaned_data['work'])
if self.cleaned_data['province']:
sqs = sqs.filter(content__icontains = self.cleaned_data['province'])
if self.cleaned_data['status']:
sqs = sqs.filter(content__icontains = self.cleaned_data['status'])
if self.cleaned_data['sex']:
sqs = sqs.filter(content__icontains = self.cleaned_data['sex'])
if self.cleaned_data['city']:
sqs = sqs.filter(content__icontains = self.cleaned_data['city'])
if self.cleaned_data['street']:
sqs = sqs.filter(content__icontains = self.cleaned_data['street'])
if self.cleaned_data['zip']:
sqs = sqs.filter(content__icontains = self.cleaned_data['zip'])
return sqs
答案 0 :(得分:0)
问题是你正在调用已经执行auto_query的父类搜索方法。你不需要这样做:
sqs = super(ContactSearchForm,self).search()
相反,这应该是您的搜索方法:
def search(self):
if not self.is_valid():
return self.no_query_found()
sqs = self.searchqueryset
for key, value in self.cleaned_data.items():
if value:
sqs = sqs.filter(content__icontains=value)
if self.load_all:
sqs = sqs.load_all()
return sqs