好吧,我已经把头发拉了好几个小时了,我想是时候寻求帮助了,因为我无法通过谷歌搜索找出为什么会发生这种情况......
本质上,我正在制作一个分类类型的应用程序,我需要一个搜索表单来搜索数据库并根据各种条件进行过滤。我正在使用 django、haystack 和 whoosh,它几乎可以完美运行,但我似乎无法让它过滤布尔变量。我已经成功地将它过滤到 Charfield 类别并且它工作得很好但是当我尝试添加基于 for_sale 布尔值(或任何布尔值)的过滤器时,它不会过滤任何东西并返回相同的结果,好像它从未被调用过(我已经检查过它实际上被调用了)。
有人有想法么?
我的模型的相关部分:
class Listing(models.Model):
SALE_CHOICES=((True, 'Items for sale'),
(False, 'Items wanted'))
for_sale = models.BooleanField(choices=SALE_CHOICES, default=True)
CAT_CHOICES = ((WOOD, "Woods"), (BRICKS, "Bricks"), etc)
category = models.CharField(max_length=6, choices = CAT_CHOICES, default = WOOD)
这是我的列表索引类:
class ListingIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
title = indexes.CharField(model_attr='title')
text_content = indexes.CharField(model_attr='text_content')
created = indexes.DateTimeField(model_attr='created')
url = indexes.CharField(model_attr='url')
price = indexes.CharField(model_attr='price', null=True)
city = indexes.CharField(model_attr='city', null=True)
category = indexes.CharField(model_attr='category')
for_sale = indexes.BooleanField(model_attr='for_sale', default=True)
def get_model(self):
return Listing
def index_queryset(self, using=None):
return self.get_model().objects.filter(expired=False).filter(verified=True)
我扩展的 SearchForm 和 SearchView:
class ListingSearchForm(FacetedSearchForm):
cat = forms.CharField(required=False, widget=forms.Select(choices=get_listings_categories()))
type = forms.CharField(required=False, widget=forms.HiddenInput)
for_sale = forms.BooleanField(required=False, widget=forms.Select(choices=get_sale_categories()))
def search(self):
# First, store the SearchQuerySet received from other processing.
sqs = super(ListingSearchForm, self).search()
# Check to see if a category was chosen.
if self.cleaned_data['cat']:
sqs = sqs.filter(category=self.cleaned_data['cat'])
# Check to see if a type was chosen.
if self.cleaned_data['for_sale']:
sqs = sqs.filter(for_sale=self.cleaned_data['for_sale'])
return sqs
class ListingSearchView(SearchView):
def extra_context(self):
extra = super(ListingSearchView, self).extra_context()
extra['post_type'] = self.request.GET.get('type', None)
extra['cat'] = self.request.GET.get('cat', None)
extra['for_sale'] = self.request.GET.get('for_sale', None)
return extra
最后是我的列表索引文本文件:
{{ object.title }}
{{ object.text_content }}
{{ object.created }}
{{ object.url }}
{{ object.category }}
{{ object.price }}
{{ object.city }}
{{ object.for_sale }}