Created
May 11, 2018 02:27
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
manage.py | |
utils.py | |
templates/ | |
- foo/ | |
- search.html | |
foo/ | |
- models.py | |
- views.py |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import unicodedata | |
def normalize(value): | |
return unicodedata.normalize('NFKD', value).encode('ASCII', 'ignore').decode('utf-8') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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