Skip to content

Instantly share code, notes, and snippets.

@rvlb
Created May 11, 2018 02:27
Show Gist options
  • Save rvlb/e907526eeac672119292a46697d3acc9 to your computer and use it in GitHub Desktop.
Save rvlb/e907526eeac672119292a46697d3acc9 to your computer and use it in GitHub Desktop.
Como fazer uma busca em Django ignorando acentuação independente de banco de dados
manage.py
utils.py
templates/
- foo/
- search.html
foo/
- models.py
- views.py
from django.dispatch import receiver
from django.db import models
from django.db.models.signals import pre_save
from utils import normalize
class Foo(models.Model):
bar = models.CharField(max_length=255)
query_string = models.CharField(max_length=255, blank='')
@receiver(pre_save, sender=Foo)
def set_foo_query_string(sender, instance, **kwargs):
instance.query_string = normalize(instance.bar)
import unicodedata
def normalize(value):
return unicodedata.normalize('NFKD', value).encode('ASCII', 'ignore').decode('utf-8')
from django.views.generic import ListView
from utils import normalize
from .models import Foo
class SearchView(ListView):
template_name = 'foo/search.html'
def get_queryset(self):
params = self.request.GET
query = params.get('q', '')
query = normalize(query)
return Foo.objects.filter(query_string__icontains=query)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment