from rest_framework.filters import SearchFilter
class UUIDSearchBackend(SearchFilter):
def get_search_terms(self, request):
params = request.query_params.get(self.search_param, '')
params = params.replace('\x00', '')
params = params.replace(',', ' ')
params_list = params.split()
new_list = []
for item in params_list:
uuid = re.match(r'[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}', item)
if uuid:
uuid = uuid.group()
uuid = re.sub(r'-', '', uuid)
new_list.append(uuid)
else:
new_list.append(item)
return new_list
这里重写了SearchFilter的get_search_terms
简单的来说就是将查询参数里面search 的内容进行分割,然后符合UUID的格式的字段去掉 - ,返回查询term的list。
在SearchFilter内部会重新将这个list拆开进行模糊搜索