From 0051941454b1923c6cab3e68e6c1caf737bc8714 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ses=C3=B3stris=20Vieira?= Date: Tue, 18 Jun 2024 18:02:09 -0300 Subject: [PATCH] =?UTF-8?q?Corrige=20filtros=20para=20funcionar=20na=20nov?= =?UTF-8?q?a=20vers=C3=A3o=20do=20Django.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- sigi/apps/convenios/filters.py | 16 ++++-- sigi/apps/eventos/admin.py | 2 + sigi/apps/ocorrencias/filters.py | 24 --------- sigi/apps/servicos/filters.py | 63 +++++++++-------------- sigi/apps/utils/filters.py | 85 ++++++++++++++++++++------------ 5 files changed, 91 insertions(+), 99 deletions(-) diff --git a/sigi/apps/convenios/filters.py b/sigi/apps/convenios/filters.py index 62eec6b..b92e03b 100644 --- a/sigi/apps/convenios/filters.py +++ b/sigi/apps/convenios/filters.py @@ -1,4 +1,5 @@ from django.contrib import admin +from django.contrib.admin.utils import build_q_object_from_lookup_parameters from django.utils.translation import gettext as _ from sigi.apps.convenios.models import Projeto @@ -49,13 +50,16 @@ class TipoProjetoFilter(admin.FieldListFilter): def queryset(self, request, queryset): value = self.value() if value is not None: - if value == "SC": + if value[-1] == "SC": queryset = queryset.filter(**{self.field_path: None}) - elif value == "CC": + elif value[-1] == "CC": queryset = queryset.exclude(**{self.field_path: None}) else: - queryset = queryset.filter(**{self.field_path: value}) - + queryset = queryset.filter( + build_q_object_from_lookup_parameters( + {self.field_path: value} + ) + ) return queryset @@ -103,5 +107,7 @@ class ExcluirTipoProjetoFilter(admin.FieldListFilter): def queryset(self, request, queryset): value = self.value() if value is not None: - queryset = queryset.exclude(**{self.field_path: value}) + queryset = queryset.exclude( + build_q_object_from_lookup_parameters({self.field_path: value}) + ) return queryset diff --git a/sigi/apps/eventos/admin.py b/sigi/apps/eventos/admin.py index 6e1b0a7..809edc1 100644 --- a/sigi/apps/eventos/admin.py +++ b/sigi/apps/eventos/admin.py @@ -80,6 +80,7 @@ class ActVigenteFilter(admin.SimpleListFilter): return queryset.exclude(act_id=None) if self.value() == "no": return queryset.filter(act_id=None) + return queryset class NumeroParticipantesFilter(admin.SimpleListFilter): @@ -102,6 +103,7 @@ class NumeroParticipantesFilter(admin.SimpleListFilter): return queryset.annotate( diferenca=F("inscritos_saberes") - F("aprovados_saberes") ).filter(diferenca__gte=10) + return queryset class MicrorregiaoFilter(AutocompleteFilter): diff --git a/sigi/apps/ocorrencias/filters.py b/sigi/apps/ocorrencias/filters.py index 3b04122..278d6ae 100644 --- a/sigi/apps/ocorrencias/filters.py +++ b/sigi/apps/ocorrencias/filters.py @@ -10,27 +10,3 @@ class ServidorRegistroFilter(admin.filters.RelatedFieldListFilter): "nome_completo" ) self.lookup_choices = [(x.id, x) for x in servidores] - - -class OcorrenciaListFilter(admin.SimpleListFilter): - title = _("Relacionadas a Mim") - parameter_name = "minhas" - - def lookups(self, request, model_admin): - if request.user.servidor is None: - return None - return ( - ("M", _("Registrados por mim")), - ("G", _("Sobre casas que gerencio")), - ) - - def queryset(self, request, queryset): - servidor = request.user.servidor - if self.value() == "M": - return queryset.filter(servidor_registro=servidor) - elif self.value() == "G": - return queryset.filter( - casa_legislativa__gerentes_interlegis=servidor - ) - else: - return queryset diff --git a/sigi/apps/servicos/filters.py b/sigi/apps/servicos/filters.py index b466902..485b313 100644 --- a/sigi/apps/servicos/filters.py +++ b/sigi/apps/servicos/filters.py @@ -4,24 +4,15 @@ from django.contrib import admin class ServicoAtivoFilter(admin.FieldListFilter): - parameter_name = None - def __init__(self, field, request, params, model, model_admin, field_path): self.model = model self.model_admin = model_admin self.parameter_name = f"{field_path}__isnull" - super().__init__( field, request, params, model, model_admin, field_path ) - self.title = _("Serviço ativo") - - if self.parameter_name in params: - value = params.pop(self.parameter_name) - self.used_parameters[self.parameter_name] = value lookup_choices = self.lookups(request, model_admin) - if lookup_choices is None: lookup_choices = () self.lookup_choices = list(lookup_choices) @@ -41,8 +32,11 @@ class ServicoAtivoFilter(admin.FieldListFilter): ] def choices(self, changelist): + value = self.value() + if isinstance(value, list): + value = value[-1] yield { - "selected": self.value() is None, + "selected": value is None, "query_string": changelist.get_query_string( remove=[self.parameter_name] ), @@ -50,7 +44,7 @@ class ServicoAtivoFilter(admin.FieldListFilter): } for lookup, title in self.lookup_choices: yield { - "selected": str(self.value()) == str(lookup), + "selected": str(value) == str(lookup), "query_string": changelist.get_query_string( {self.parameter_name: lookup} ), @@ -77,32 +71,23 @@ class DataUtimoUsoFilter(admin.SimpleListFilter): if self.value() is not None: queryset = queryset.exclude(tipo_servico__string_pesquisa="") if self.value() == "err": - queryset = queryset.exclude(erro_atualizacao="") - elif self.value() == "year": + return queryset.exclude(erro_atualizacao="") + if self.value() == "year": limite = date.today() - timedelta(days=366) - queryset = queryset.filter(data_ultimo_uso__lte=limite) - else: - de = date.today() - ( - timedelta(days=365) - if self.value() == "semester" - else timedelta(days=6 * 30) - if self.value() == "quarter" - else timedelta(days=3 * 30) - if self.value() == "month" - else timedelta(days=30) - if self.value() == "week" - else timedelta(days=6) - ) - ate = date.today() - ( - timedelta(days=6 * 30 + 1) - if self.value() == "semester" - else timedelta(days=3 * 30 + 1) - if self.value() == "quarter" - else timedelta(days=31) - if self.value() == "month" - else timedelta(days=7) - if self.value() == "week" - else timedelta(days=0) - ) - queryset = queryset.filter(data_ultimo_uso__range=(de, ate)) - return queryset + return queryset.filter(data_ultimo_uso__lte=limite) + if self.value() == "updated": + limite = date.today() - timedelta(days=7) + return queryset.filter(data_ultimo_uso__gte=limite) + if self.value() == "semester": + de = date.today() - timedelta(days=365) + ate = date.today() - timedelta(days=6 * 30 + 1) + elif self.value() == "quarter": + de = date.today() - timedelta(days=6 * 30) + ate = date.today() - timedelta(days=3 * 30 + 1) + elif self.value() == "month": + de = date.today() - timedelta(days=3 * 30) + ate = date.today() - timedelta(days=31) + elif self.value() == "week": + de = date.today() - timedelta(days=30) + ate = date.today() - timedelta(days=7) + return queryset.filter(data_ultimo_uso__range=(de, ate)) diff --git a/sigi/apps/utils/filters.py b/sigi/apps/utils/filters.py index 1a20d50..d5d4373 100644 --- a/sigi/apps/utils/filters.py +++ b/sigi/apps/utils/filters.py @@ -1,11 +1,21 @@ import string from math import log10 from django import forms -from django.db.models import Q from django.contrib import admin from django.contrib.admin.options import IncorrectLookupParameters -from django.utils.translation import ngettext, gettext as _ +from django.contrib.admin.utils import ( + build_q_object_from_lookup_parameters, + prepare_lookup_value, +) from django.core.exceptions import ValidationError +from django.utils.translation import ngettext, gettext as _ + + +def filter_single_value(value): + if isinstance(value, list): + return value[0] + else: + return value class NotEmptyableField(Exception): @@ -14,7 +24,7 @@ class NotEmptyableField(Exception): class AlphabeticFilter(admin.SimpleListFilter): title = "" - parameter_name = "" + parameter_name = None def lookups(self, request, model_admin): return ( @@ -26,10 +36,13 @@ class AlphabeticFilter(admin.SimpleListFilter): ) def queryset(self, request, queryset): - if self.value(): - return queryset.filter( - (self.parameter_name + "__istartswith", self.value()) + if self.value() is not None: + queryset = queryset.filter( + build_q_object_from_lookup_parameters( + {self.parameter_name + "__istartswith": self.value()} + ) ) + return queryset class RangeFilter(admin.FieldListFilter): @@ -45,9 +58,6 @@ class RangeFilter(admin.FieldListFilter): field, request, params, model, model_admin, field_path ) - if self.parameter_name in params: - value = params.pop(self.parameter_name) - self.used_parameters[self.parameter_name] = value lookup_choices = self.lookups(request, model_admin) if lookup_choices is None: @@ -65,10 +75,10 @@ class RangeFilter(admin.FieldListFilter): value = tudo[i * passo] if value > 100: if value > 1000: - l = int(log10(value)) + log_val = int(log10(value)) else: - l = int(log10(value)) - 1 - value = value // (10**l) * (10**l) + log_val = int(log10(value)) - 1 + value = value // (10**log_val) * (10**log_val) yield (i, ultimo, value) ultimo = value @@ -78,18 +88,18 @@ class RangeFilter(admin.FieldListFilter): def humanize(num): if num < 1000: return num - l = int(log10(num)) - if l < 6: + log_val = int(log10(num)) + if log_val < 6: return ngettext( f"{num//10**3} mil", f"{num//10**3} mil", num // 10**3 ) - elif l < 9: + elif log_val < 9: return ngettext( f"{num//10**6} milhão", f"{num//10**6} milhões", num // 10**6, ) - elif l < 12: + elif log_val < 12: return ngettext( f"{num//10**9} bilhão", f"{num//10**9} bilhões", @@ -114,7 +124,10 @@ class RangeFilter(admin.FieldListFilter): return self.model.objects.exists() def value(self): - return self.used_parameters.get(self.parameter_name) + value = self.used_parameters.get(self.parameter_name) + if isinstance(value, list): + return value[-1] + return value def expected_parameters(self): return [ @@ -131,7 +144,7 @@ class RangeFilter(admin.FieldListFilter): } for lookup, title in self.lookup_choices: yield { - "selected": self.value() == str(lookup), + "selected": str(lookup) == self.value(), "query_string": changelist.get_query_string( {self.parameter_name: lookup} ), @@ -141,7 +154,7 @@ class RangeFilter(admin.FieldListFilter): def queryset(self, request, queryset): try: for value, min, max in self.ranges(self.model): - if self.value() == str(value): + if str(value) == self.value(): return queryset.filter( (f"{self.field_path}__gte", min), (f"{self.field_path}__lt", max), @@ -159,15 +172,20 @@ class DateRangeFilter(admin.FieldListFilter): self.model = model self.model_admin = model_admin self.lookup_kwargs = [f"{field_path}__gte", f"{field_path}__lte"] - + form_data = {} + for p in self.expected_parameters(): + if p in params: + value = params.pop(p)[-1] + form_data[p] = prepare_lookup_value( + p, value, self.list_separator + ) super().__init__( field, request, params, model, model_admin, field_path ) - - form = self.get_date_form(self.used_parameters) + form = self.get_date_form(form_data) if form.is_valid(): self.used_parameters = { - key: value + key: [value] for key, value in form.cleaned_data.items() if value is not None } @@ -181,12 +199,15 @@ class DateRangeFilter(admin.FieldListFilter): return self.lookup_kwargs def choices(self, changelist): + form_params = { + key: value[-1] for key, value in self.used_parameters.items() + } return [ { "query_string": changelist.get_query_string( remove=self.lookup_kwargs ), - "form": self.get_date_form(self.used_parameters, changelist), + "form": self.get_date_form(form_params, changelist), } ] @@ -201,13 +222,15 @@ class DateRangeFilter(admin.FieldListFilter): "placeholder": ( _("De") if "__gte" in name else _("Até") ), - "data-clear": changelist.get_query_string( - remove=[ - name, - ] - ) - if changelist - else "", + "data-clear": ( + changelist.get_query_string( + remove=[ + name, + ] + ) + if changelist + else "" + ), } ), )