通过'添加'顺序Django的Haystack选项

时间:2014-06-19 19:42:02

标签: python django django-haystack

我正在尝试向ModelSearchForm添加“排序依据”选项,以便您可以按日期,名称等进行排序。截至目前,这就是我所拥有的。我目前正试图让它与'created'字段一起工作,这是一个日期时间。问题是它根本就没有订购。

我试过

class CustomSearchForm(ModelSearchForm):
    order_choices= [('date', 'Date'),
                ('name', 'Name'),
                ('model', 'Model')]
    order = forms.ChoiceField(choices=order_choices, widget=forms.RadioSelect(), initial='date', required=False)
    desc = forms.ChoiceField(choices=[('y', 'Descending'), ('n', 'Ascending')], widget=forms.RadioSelect(), label='', initial='y', required=False)


    def search(self):
        sqs = super(CustomSearchForm, self).search()
        if not self.is_valid():
            return self.no_query_found()

        if self.cleaned_data['order'] == 'date':
            if self.cleaned_data['desc'] == 'y':
                # it successfully gets to this point, but this next line does nothing...
                sqs.order_by('-created')
            else:
                sqs.order_by('created')

        return sqs

我也试过这个:

sqs.order_by('File__created')

同样的结果(根本没有订购。)

在我的模型文件中:

class File(models.Model):
    file_sequence = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=100, blank=True)
    folder_sequence = models.ForeignKey(Folders, db_column='folder_sequence')
    created = models.DateTimeField(blank=True, null=True)
    notes = models.TextField(blank=True)

我无法理解我的生活。我是以错误的方式来做这件事的吗?我很惊讶Haystack已经没有内置这个功能了。

编辑:另外,我正在使用Whoosh作为后端。

search_indexes.py:

class FilesIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.NgramField(document=True, use_template=True)
    created = indexes.DateTimeField(model_attr='created')
    def get_model(self):
        return Files

    def index_queryset(self, using=None):
        """Used when the entire index for model is updated."""
        return self.get_model().objects.all().select_related() 

1 个答案:

答案 0 :(得分:0)

哇,我不敢相信我错过了这个。

    if self.cleaned_data['order'] == 'date':
        if self.cleaned_data['desc'] == 'y':
            sqs.order_by('-created')
        else:
            sqs.order_by('created')

需要

    if self.cleaned_data['order'] == 'date':
        if self.cleaned_data['desc'] == 'y':
            sqs = sqs.order_by('-created')
        else:
            sqs = sqs.order_by('created')