我只想知道在执行查询之前如何删除搜索词上的所有重音符号(以及在哪里)。
我使用Django 1.9。
search_fields = ('name', )
filter_backends = (OrderingFilter, SearchFilter)
ordering = ('name', )
我的序列化器:
class MySerializer(serializers.ModelSerializer):
another = AnotherSerializer()
class Meta:
model = My_model
fields = ('id', 'name', 'position')
我的模特:
class My_model(models.Model):
class Meta:
ordering = ['index']
name = models.CharField(max_length=250, verbose_name=_("My_model name"))
another = models.ForeignKey(Another, verbose_name=_("Another"))
@staticmethod
def autocomplete_search_fields():
return ("id__icontains", "name__icontains", "another__address__icontains")
def __unicode__(self):
return "%s %s : %s - %s" % (_("My_model"), self.pk, self.name, self.address)
最佳答案
您可以编写继承自SearchFilter的自己的CustomisedSearchFilter,并覆盖get_search_terms()方法以执行您喜欢的任何操作,删除重音符号等。在这里,以下代码只是SearchFilter的原始代码:
class SearchFilter(BaseFilterBackend):
def get_search_terms(self, request):
"""
Search terms are set by a ?search=... query parameter,
and may be comma and/or whitespace delimited.
"""
params = request.query_params.get(self.search_param, '')
return params.replace(',', ' ').split()
并且您的代码应如下所示:
class CustomisedSearchFilter(SearchFilter):
def get_search_terms(self, request):
params = request.query_params.get(self.search_param, '')
terms = params.replace(',', ' ').split()
# do whatever you want about the terms
# ...
import unidecode
terms = [unidecode.unidecode(term) for term in terms]
return terms
关于python - 删除搜索词Django Rest Framework中的重音符号,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49511079/