在 django-filters 的 FilterSet 中使用全文搜索的最佳方法?

vad*_*imb 5 django django-filters django-rest-framework

我的应用程序使用rest-frameworkdjango-filter. 我用它FilterSet来提供文章过滤列表(ModelViewSetdate

from django_filters import rest_framework as filters

class ArticleFilter(filters.FilterSet):
    start_date = filters.DateTimeFilter(field_name='pub_date', lookup_expr='gte')
    end_date = filters.DateTimeFilter(field_name='pub_date', lookup_expr='lte') 

    class Meta:
        model = Article
        fields = ['pub_date']
Run Code Online (Sandbox Code Playgroud)

我想将搜索框添加到我的应用程序中,因此我需要另一个过滤器,它将在我的模型中使用全文搜索Article。我要搜索的字段是titledescription。我决定添加search带有method这样的参数的字段:

from django_filters import rest_framework as filters
from django.contrib.postgres.search import SearchVector

class ArticleFilter(filters.FilterSet):
    start_date = filters.DateTimeFilter(field_name='pub_date', lookup_expr='gte')
    end_date = filters.DateTimeFilter(field_name='pub_date', lookup_expr='lte')
    search = filters.CharFilter(method='filter_search')

    def filter_search(self, queryset, name, value):
        return queryset.annotate(search=SearchVector('title', 'description')).filter(search=value)

    class Meta:
        model = Article
        fields = ['pub_date']
Run Code Online (Sandbox Code Playgroud)

它有效,但我不确定这是使用全文搜索过滤的最佳方式。我错过了什么还是这种方法可以?

Jas*_*son 1

这对于简单的文本搜索来说是可以的,因为在小型数据库中没有太多文本可供查找。

当您进入更大的领域时,您需要为此优化数据库或转向专用搜索引擎,例如 Solr 或 ElasticSearch。Postgres 有一个关于全文搜索的部分, mysql也是如此。