1
resposta

CRIAÇÃO DE FILTRO NA API DJANGO REST

Bom dia a todos.

Estou tentando criar o filtro na API seguindo as configurações, porém está dando a mensagem abaixo.

Watching for file changes with StatReloader
Performing system checks...

Exception in thread django-main-thread:
Traceback (most recent call last):
  File "/home/hugo/anaconda3/lib/python3.8/threading.py", line 932, in _bootstrap_inner
    self.run()
  File "/home/hugo/anaconda3/lib/python3.8/threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "/home/hugo/Área de Trabalho/django_api_2/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "/home/hugo/Área de Trabalho/django_api_2/venv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 134, in inner_run
    self.check(display_num_errors=True)
  File "/home/hugo/Área de Trabalho/django_api_2/venv/lib/python3.8/site-packages/django/core/management/base.py", line 487, in check
    all_issues = checks.run_checks(
  File "/home/hugo/Área de Trabalho/django_api_2/venv/lib/python3.8/site-packages/django/core/checks/registry.py", line 88, in run_checks
    new_errors = check(app_configs=app_configs, databases=databases)
  File "/home/hugo/Área de Trabalho/django_api_2/venv/lib/python3.8/site-packages/django/core/checks/urls.py", line 42, in check_url_namespaces_unique
    all_namespaces = _load_all_namespaces(resolver)
  File "/home/hugo/Área de Trabalho/django_api_2/venv/lib/python3.8/site-packages/django/core/checks/urls.py", line 61, in _load_all_namespaces
    url_patterns = getattr(resolver, "url_patterns", [])
  File "/home/hugo/Área de Trabalho/django_api_2/venv/lib/python3.8/site-packages/django/utils/functional.py", line 49, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/hugo/Área de Trabalho/django_api_2/venv/lib/python3.8/site-packages/django/urls/resolvers.py", line 696, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "/home/hugo/Área de Trabalho/django_api_2/venv/lib/python3.8/site-packages/django/utils/functional.py", line 49, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/hugo/Área de Trabalho/django_api_2/venv/lib/python3.8/site-packages/django/urls/resolvers.py", line 689, in urlconf_module
    return import_module(self.urlconf_name)
  File "/home/hugo/anaconda3/lib/python3.8/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 783, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/home/hugo/Área de Trabalho/django_api_2/setup/urls.py", line 3, in <module>
    from rest_framework import routers
  File "/home/hugo/Área de Trabalho/django_api_2/venv/lib/python3.8/site-packages/rest_framework/routers.py", line 19, in <module>
    from django.conf.urls import url
ImportError: cannot import name 'url' from 'django.conf.urls' (/home/hugo/Área de Trabalho/django_api_2/venv/lib/python3.8/site-packages/django/conf/urls/__init__.py)

Abaixo seguem os códigos configurados conforme vídeo aula.

clientes/views.py

from rest_framework import viewsets, filters
from clientes.serializers import ClienteSerializer
from clientes.models import Cliente
from django_filters.rest_framework import DjangoFilterBackend

class ClientesViewSet(viewsets.ModelViewSet):
    """Listando clientes"""
    queryset = Cliente.objects.all()
    serializer_class = ClienteSerializer
    filter_backends = [DjangoFilterBackend, filters.OrderingFilter]
    ordering_fields = ['nome']
1 resposta

Olá Hugo. Tudo bem? Espero que sim.

Pelo que vi no seu código, você deixou e informar algumas coisas. A primeira é indicar que haverá o filtro de busca no seu filter_backends adicionando o paramêtro filters.SearchFilter. A segunda seria indicar quais campos serão buscados por meio do search_fields.

Ao meu ver ficará assim:

from rest_framework import viewsets, filters
from clientes.serializers import ClienteSerializer
from clientes.models import Cliente
from django_filters.rest_framework import DjangoFilterBackend

class ClientesViewSet(viewsets.ModelViewSet):
    """Listando clientes"""
    queryset = Cliente.objects.all()
    serializer_class = ClienteSerializer
    filter_backends = [DjangoFilterBackend, filters.OrderingFilter, filters.SearchFilter]
    ordering_fields = ['nome']
    search_fields = ['nome']

Espero que funcione e seja de ajuda para você. Abraços.