Browse Source

Corrige filtros para funcionar na nova versão do Django.

dependabot/pip/requirements/djangorestframework-3.15.2 3.0.88
Sesóstris Vieira 6 months ago
parent
commit
0051941454
  1. 16
      sigi/apps/convenios/filters.py
  2. 2
      sigi/apps/eventos/admin.py
  3. 24
      sigi/apps/ocorrencias/filters.py
  4. 63
      sigi/apps/servicos/filters.py
  5. 75
      sigi/apps/utils/filters.py

16
sigi/apps/convenios/filters.py

@ -1,4 +1,5 @@
from django.contrib import admin 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 django.utils.translation import gettext as _
from sigi.apps.convenios.models import Projeto from sigi.apps.convenios.models import Projeto
@ -49,13 +50,16 @@ class TipoProjetoFilter(admin.FieldListFilter):
def queryset(self, request, queryset): def queryset(self, request, queryset):
value = self.value() value = self.value()
if value is not None: if value is not None:
if value == "SC": if value[-1] == "SC":
queryset = queryset.filter(**{self.field_path: None}) queryset = queryset.filter(**{self.field_path: None})
elif value == "CC": elif value[-1] == "CC":
queryset = queryset.exclude(**{self.field_path: None}) queryset = queryset.exclude(**{self.field_path: None})
else: else:
queryset = queryset.filter(**{self.field_path: value}) queryset = queryset.filter(
build_q_object_from_lookup_parameters(
{self.field_path: value}
)
)
return queryset return queryset
@ -103,5 +107,7 @@ class ExcluirTipoProjetoFilter(admin.FieldListFilter):
def queryset(self, request, queryset): def queryset(self, request, queryset):
value = self.value() value = self.value()
if value is not None: 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 return queryset

2
sigi/apps/eventos/admin.py

@ -80,6 +80,7 @@ class ActVigenteFilter(admin.SimpleListFilter):
return queryset.exclude(act_id=None) return queryset.exclude(act_id=None)
if self.value() == "no": if self.value() == "no":
return queryset.filter(act_id=None) return queryset.filter(act_id=None)
return queryset
class NumeroParticipantesFilter(admin.SimpleListFilter): class NumeroParticipantesFilter(admin.SimpleListFilter):
@ -102,6 +103,7 @@ class NumeroParticipantesFilter(admin.SimpleListFilter):
return queryset.annotate( return queryset.annotate(
diferenca=F("inscritos_saberes") - F("aprovados_saberes") diferenca=F("inscritos_saberes") - F("aprovados_saberes")
).filter(diferenca__gte=10) ).filter(diferenca__gte=10)
return queryset
class MicrorregiaoFilter(AutocompleteFilter): class MicrorregiaoFilter(AutocompleteFilter):

24
sigi/apps/ocorrencias/filters.py

@ -10,27 +10,3 @@ class ServidorRegistroFilter(admin.filters.RelatedFieldListFilter):
"nome_completo" "nome_completo"
) )
self.lookup_choices = [(x.id, x) for x in servidores] 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

63
sigi/apps/servicos/filters.py

@ -4,24 +4,15 @@ from django.contrib import admin
class ServicoAtivoFilter(admin.FieldListFilter): class ServicoAtivoFilter(admin.FieldListFilter):
parameter_name = None
def __init__(self, field, request, params, model, model_admin, field_path): def __init__(self, field, request, params, model, model_admin, field_path):
self.model = model self.model = model
self.model_admin = model_admin self.model_admin = model_admin
self.parameter_name = f"{field_path}__isnull" self.parameter_name = f"{field_path}__isnull"
super().__init__( super().__init__(
field, request, params, model, model_admin, field_path field, request, params, model, model_admin, field_path
) )
self.title = _("Serviço ativo") 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) lookup_choices = self.lookups(request, model_admin)
if lookup_choices is None: if lookup_choices is None:
lookup_choices = () lookup_choices = ()
self.lookup_choices = list(lookup_choices) self.lookup_choices = list(lookup_choices)
@ -41,8 +32,11 @@ class ServicoAtivoFilter(admin.FieldListFilter):
] ]
def choices(self, changelist): def choices(self, changelist):
value = self.value()
if isinstance(value, list):
value = value[-1]
yield { yield {
"selected": self.value() is None, "selected": value is None,
"query_string": changelist.get_query_string( "query_string": changelist.get_query_string(
remove=[self.parameter_name] remove=[self.parameter_name]
), ),
@ -50,7 +44,7 @@ class ServicoAtivoFilter(admin.FieldListFilter):
} }
for lookup, title in self.lookup_choices: for lookup, title in self.lookup_choices:
yield { yield {
"selected": str(self.value()) == str(lookup), "selected": str(value) == str(lookup),
"query_string": changelist.get_query_string( "query_string": changelist.get_query_string(
{self.parameter_name: lookup} {self.parameter_name: lookup}
), ),
@ -77,32 +71,23 @@ class DataUtimoUsoFilter(admin.SimpleListFilter):
if self.value() is not None: if self.value() is not None:
queryset = queryset.exclude(tipo_servico__string_pesquisa="") queryset = queryset.exclude(tipo_servico__string_pesquisa="")
if self.value() == "err": if self.value() == "err":
queryset = queryset.exclude(erro_atualizacao="") return queryset.exclude(erro_atualizacao="")
elif self.value() == "year": if self.value() == "year":
limite = date.today() - timedelta(days=366) limite = date.today() - timedelta(days=366)
queryset = queryset.filter(data_ultimo_uso__lte=limite) return queryset.filter(data_ultimo_uso__lte=limite)
else: if self.value() == "updated":
de = date.today() - ( limite = date.today() - timedelta(days=7)
timedelta(days=365) return queryset.filter(data_ultimo_uso__gte=limite)
if self.value() == "semester" if self.value() == "semester":
else timedelta(days=6 * 30) de = date.today() - timedelta(days=365)
if self.value() == "quarter" ate = date.today() - timedelta(days=6 * 30 + 1)
else timedelta(days=3 * 30) elif self.value() == "quarter":
if self.value() == "month" de = date.today() - timedelta(days=6 * 30)
else timedelta(days=30) ate = date.today() - timedelta(days=3 * 30 + 1)
if self.value() == "week" elif self.value() == "month":
else timedelta(days=6) de = date.today() - timedelta(days=3 * 30)
) ate = date.today() - timedelta(days=31)
ate = date.today() - ( elif self.value() == "week":
timedelta(days=6 * 30 + 1) de = date.today() - timedelta(days=30)
if self.value() == "semester" ate = date.today() - timedelta(days=7)
else timedelta(days=3 * 30 + 1) return queryset.filter(data_ultimo_uso__range=(de, ate))
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

75
sigi/apps/utils/filters.py

@ -1,11 +1,21 @@
import string import string
from math import log10 from math import log10
from django import forms from django import forms
from django.db.models import Q
from django.contrib import admin from django.contrib import admin
from django.contrib.admin.options import IncorrectLookupParameters 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.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): class NotEmptyableField(Exception):
@ -14,7 +24,7 @@ class NotEmptyableField(Exception):
class AlphabeticFilter(admin.SimpleListFilter): class AlphabeticFilter(admin.SimpleListFilter):
title = "" title = ""
parameter_name = "" parameter_name = None
def lookups(self, request, model_admin): def lookups(self, request, model_admin):
return ( return (
@ -26,10 +36,13 @@ class AlphabeticFilter(admin.SimpleListFilter):
) )
def queryset(self, request, queryset): def queryset(self, request, queryset):
if self.value(): if self.value() is not None:
return queryset.filter( queryset = queryset.filter(
(self.parameter_name + "__istartswith", self.value()) build_q_object_from_lookup_parameters(
{self.parameter_name + "__istartswith": self.value()}
) )
)
return queryset
class RangeFilter(admin.FieldListFilter): class RangeFilter(admin.FieldListFilter):
@ -45,9 +58,6 @@ class RangeFilter(admin.FieldListFilter):
field, request, params, model, model_admin, field_path 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) lookup_choices = self.lookups(request, model_admin)
if lookup_choices is None: if lookup_choices is None:
@ -65,10 +75,10 @@ class RangeFilter(admin.FieldListFilter):
value = tudo[i * passo] value = tudo[i * passo]
if value > 100: if value > 100:
if value > 1000: if value > 1000:
l = int(log10(value)) log_val = int(log10(value))
else: else:
l = int(log10(value)) - 1 log_val = int(log10(value)) - 1
value = value // (10**l) * (10**l) value = value // (10**log_val) * (10**log_val)
yield (i, ultimo, value) yield (i, ultimo, value)
ultimo = value ultimo = value
@ -78,18 +88,18 @@ class RangeFilter(admin.FieldListFilter):
def humanize(num): def humanize(num):
if num < 1000: if num < 1000:
return num return num
l = int(log10(num)) log_val = int(log10(num))
if l < 6: if log_val < 6:
return ngettext( return ngettext(
f"{num//10**3} mil", f"{num//10**3} mil", num // 10**3 f"{num//10**3} mil", f"{num//10**3} mil", num // 10**3
) )
elif l < 9: elif log_val < 9:
return ngettext( return ngettext(
f"{num//10**6} milhão", f"{num//10**6} milhão",
f"{num//10**6} milhões", f"{num//10**6} milhões",
num // 10**6, num // 10**6,
) )
elif l < 12: elif log_val < 12:
return ngettext( return ngettext(
f"{num//10**9} bilhão", f"{num//10**9} bilhão",
f"{num//10**9} bilhões", f"{num//10**9} bilhões",
@ -114,7 +124,10 @@ class RangeFilter(admin.FieldListFilter):
return self.model.objects.exists() return self.model.objects.exists()
def value(self): 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): def expected_parameters(self):
return [ return [
@ -131,7 +144,7 @@ class RangeFilter(admin.FieldListFilter):
} }
for lookup, title in self.lookup_choices: for lookup, title in self.lookup_choices:
yield { yield {
"selected": self.value() == str(lookup), "selected": str(lookup) == self.value(),
"query_string": changelist.get_query_string( "query_string": changelist.get_query_string(
{self.parameter_name: lookup} {self.parameter_name: lookup}
), ),
@ -141,7 +154,7 @@ class RangeFilter(admin.FieldListFilter):
def queryset(self, request, queryset): def queryset(self, request, queryset):
try: try:
for value, min, max in self.ranges(self.model): for value, min, max in self.ranges(self.model):
if self.value() == str(value): if str(value) == self.value():
return queryset.filter( return queryset.filter(
(f"{self.field_path}__gte", min), (f"{self.field_path}__gte", min),
(f"{self.field_path}__lt", max), (f"{self.field_path}__lt", max),
@ -159,15 +172,20 @@ class DateRangeFilter(admin.FieldListFilter):
self.model = model self.model = model
self.model_admin = model_admin self.model_admin = model_admin
self.lookup_kwargs = [f"{field_path}__gte", f"{field_path}__lte"] 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__( super().__init__(
field, request, params, model, model_admin, field_path field, request, params, model, model_admin, field_path
) )
form = self.get_date_form(form_data)
form = self.get_date_form(self.used_parameters)
if form.is_valid(): if form.is_valid():
self.used_parameters = { self.used_parameters = {
key: value key: [value]
for key, value in form.cleaned_data.items() for key, value in form.cleaned_data.items()
if value is not None if value is not None
} }
@ -181,12 +199,15 @@ class DateRangeFilter(admin.FieldListFilter):
return self.lookup_kwargs return self.lookup_kwargs
def choices(self, changelist): def choices(self, changelist):
form_params = {
key: value[-1] for key, value in self.used_parameters.items()
}
return [ return [
{ {
"query_string": changelist.get_query_string( "query_string": changelist.get_query_string(
remove=self.lookup_kwargs 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": ( "placeholder": (
_("De") if "__gte" in name else _("Até") _("De") if "__gte" in name else _("Até")
), ),
"data-clear": changelist.get_query_string( "data-clear": (
changelist.get_query_string(
remove=[ remove=[
name, name,
] ]
) )
if changelist if changelist
else "", else ""
),
} }
), ),
) )

Loading…
Cancel
Save