【发布时间】:2020-08-10 13:04:21
【问题描述】:
我正在为我的 API 实现一个搜索功能,以便在请求时返回对象的属性。到目前为止,我已经尝试使用 全文搜索 ,它是可用的,但它有这些烦人的事情:必须正确拼写单词才能返回结果和部分搜索,例如“appl”而不是“苹果”,行不通。我也尝试过 Trigram Similarity,但对于长句子它失败了。如何在Django中实现既准确又模糊的搜索功能?
这行得通
这行不通
这是我的 views.py
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework import status
from rest_framework.decorators import api_view
from .models import Object_Locations
from .serializers import Object_LocationsSerializer
from django.contrib.postgres.search import SearchVector, SearchQuery
def index(request):
return render(request, 'main/base.html', {})
@api_view(['GET',])
def LocationsList(request):
if request.method == 'GET':
vector = SearchVector('name', 'desc', 'catergory')
query = request.GET.get('search')
if query:
locations = Object_Locations.objects.annotate(search=vector,).filter(search=SearchQuery(query))
else:
locations = Object_Locations.objects.all()
serializer = Object_LocationsSerializer(locations, many=True)
return Response(serializer.data)
【问题讨论】:
标签: django python-3.x postgresql django-rest-framework full-text-search