可以自己写一个 middleware 捕获 request 放到 全局/模块/单例
例如我自己写的 middleware:
```python
import contextvars
import django.http
GLOBAL_REQUEST = contextvars.ContextVar("GLOBAL_REQUEST", default=None)
class GlobalRequest:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
global GLOBAL_REQUEST
GLOBAL_REQUEST.set(request)
return self.get_response(request)
# 用这个获取 request 实例
def get_request() -> django.http.HttpRequest:
return GLOBAL_REQUEST.get()
```
可以,get_search_results 参数 search_term 就是搜索框的内容(类型 str ),对 queryset 参数进行 filter 然后返回即可
排除的话,可以考虑用数据库的全文索引,实现简单,性能尚可
例如
```
def get_search_results(self, request, queryset, search_term):
if not search_term:
return super().get_search_results(request, queryset, search_term)
return queryset.filter(seo__search=search_term), False
#end get_search_results
```
```
class SearchLookup(models.Lookup):
lookup_name = "search"
def as_mysql(self, compiler, connection):
lhs, lhs_params = self.process_lhs(compiler, connection)
rhs, rhs_params = self.process_rhs(compiler, connection)
params = lhs_params + rhs_params
return "MATCH (%s) AGAINST (%s IN BOOLEAN MODE)" % (lhs, rhs), params
#end as_mysql
#end - SearchLookup
```