Django Haystack为搜索添加了额外的输入

时间:2011-11-17 13:19:09

标签: python django django-haystack

我的干草堆搜索目前在以下型号上搜索效果很好:

class AdminEntry(models.Model):
    product = models.ForeignKey('Product')
    number_entries = models.IntegerField(max_length=3,  null=True)

我的search_indexes.py

class AdminEntryIndex(SearchIndex):
    text = CharField(document=True, use_template=True)
    author = CharField(model_attr='product__author')
    title = CharField(model_attr='product__title')
    desc = CharField(model_attr='product__desc')

    def get_queryset(self):
        return AdminEntry.objects.all()

site.register(AdminEntry, AdminEntryIndex)

但是现在我想在我的搜索表单的下拉列表中添加额外的搜索参数,其中包含2个值['Admin', 'Staff'],因为我添加了另一个模型:

class StaffEntry(models.Model):
    product = models.ForeignKey('Product')
    number_entries = models.IntegerField(max_length=3,  null=True)

如果所选下拉列表为“员工”,并且StaffEntry为“管理员”,则我希望我的搜索在AdminEntry上搜索。有人可以帮我解决如何使用Haystack和Whoosh实现这个目标吗?提前谢谢。

2 个答案:

答案 0 :(得分:0)

你所追求的是ModelSearchForm:

http://django-haystack.readthedocs.org/en/latest/views_and_forms.html#modelsearchform

使用此代替默认的SearchForm,您将获得每个索引模型的复选框。如果您扩展表单,则可以将其更改为选择而不是复选框。

有关如何在视图中使用自定义表单的信息,请参阅http://django-haystack.readthedocs.org/en/latest/views_and_forms.html#views

答案 1 :(得分:0)

<强> forms.py

类搜索(SearchForm):

         OPTIONS = [
                ('staff','Staff'),
                ('admin','Admin')
               ]

          option = forms.ChoiceField(
                    widget=forms.Select(
                        attrs={'class':'cd-select','id':'cd-dropdown'}),
                        label='',
                        choices=OPTIONS,
                        )
         def __init__(self, *args, **kwargs):
             super(Search, self).__init__(*args, **kwargs)
             self.initial['option'] = 'staff'
             self.fields['q'].label = ''



        def search(self):
            if not self.is_valid():
                 return self.no_query_found()
            if not self.cleaned_data.get('q'):
                 return self.no_query_found()
            sqs = self.searchqueryset.auto_query(self.cleaned_data['q'])

            if self.cleaned_data['option'] == 'staff':
                 sqs = SearchQuerySet().auto_query(self.cleaned_data['q']).models(Staff)
            elif self.cleaned_data['option'] == 'admin':
                 sqs = SearchQuerySet().auto_query(self.cleaned_data['q']).models(Admin)
            if self.load_all:
                 sqs = sqs.load_all()
            return sqs