diff options
Diffstat (limited to 'ishtar_common')
| -rw-r--r-- | ishtar_common/models_common.py | 3 | ||||
| -rw-r--r-- | ishtar_common/views_item.py | 86 | 
2 files changed, 61 insertions, 28 deletions
diff --git a/ishtar_common/models_common.py b/ishtar_common/models_common.py index 3f54dd5b8..e6fc8c209 100644 --- a/ishtar_common/models_common.py +++ b/ishtar_common/models_common.py @@ -837,6 +837,9 @@ class FullSearch(models.Model):      DYNAMIC_REQUESTS = {}      ALT_NAMES = {} +    BOOL_FIELDS = [] +    REVERSED_BOOL_FIELDS = [] +    CALLABLE_BOOL_FIELDS = []      BASE_SEARCH_VECTORS = []      PROPERTY_SEARCH_VECTORS = []      INT_SEARCH_VECTORS = [] diff --git a/ishtar_common/views_item.py b/ishtar_common/views_item.py index 88f20020b..404df6f90 100644 --- a/ishtar_common/views_item.py +++ b/ishtar_common/views_item.py @@ -14,6 +14,7 @@ from tempfile import NamedTemporaryFile  import unidecode  from django.conf import settings +from django.contrib.contenttypes.models import ContentType  from django.contrib.gis.geos import GEOSException  from django.contrib.staticfiles.templatetags.staticfiles import static  from django.core.cache import cache @@ -292,8 +293,7 @@ def show_source_item(request, source_id, model, name, base_dct, extra_dct):      models_rest.ApiExternalSource.objects.get()      # TODO: check permissions      try: -        src = models_rest.ApiExternalSource.objects.get( -            pk=source_id) +        src = models_rest.ApiExternalSource.objects.get(pk=source_id)      except models_rest.ApiExternalSource.DoesNotExist:          return HttpResponse("{}", content_type="text/plain")      url = src.url @@ -360,8 +360,7 @@ def show_item(model, name, extra_dct=None, model_for_perms=None):          dct["sheet_id"] = f"{name}-{pk}"          dct["window_id"] = f"{name}-{pk}-{datetime.datetime.now().strftime('%M%s')}"          if pk.startswith("source-"): -            return show_source_item( -                request, pk, model, name, dct, extra_dct) +            return show_source_item(request, pk, model, name, dct, extra_dct)          try:              item = q.get(pk=pk)          except (ObjectDoesNotExist, ValueError): @@ -537,8 +536,11 @@ def _get_values(request, val):          if callable(v):              v = v()          try: -            if not isinstance(v, (models.Person, models.Organization)) and\ -                    hasattr(v, "url") and v.url: +            if ( +                not isinstance(v, (models.Person, models.Organization)) +                and hasattr(v, "url") +                and v.url +            ):                  v = (                      (request.is_secure() and "https" or "http")                      + "://" @@ -1443,7 +1445,7 @@ def _get_data_from_query_old(                      new_vals = []                      for val in vals:                          if ky.endswith("__count"): -                            new_vals += [getattr(val, ky[:-len("__count")]).count()] +                            new_vals += [getattr(val, ky[: -len("__count")]).count()]                          elif hasattr(val, "all"):  # manage related objects                              val = list(val.all())                              for v in val: @@ -1505,7 +1507,7 @@ def _get_json_stats(          if not stat:              continue          if stat.endswith("__year"): -            q = q.annotate(**{stat: ExtractYear(stat[:-len("__year")])}) +            q = q.annotate(**{stat: ExtractYear(stat[: -len("__year")])})          value_keys.append(stat)      q = q.values(*value_keys)      if stats_sum_variable == "pk": @@ -1596,7 +1598,7 @@ def get_item(          no_link=False,          no_limit=False,          return_query=False, -        **dct +        **dct,      ):          available_perms = []          if specific_perms: @@ -1715,8 +1717,13 @@ def get_item(              [                  (                      field.name, -                    field.name + (hasattr(field, "remote_field") -                                  and field.remote_field and "__pk" or ""), +                    field.name +                    + ( +                        hasattr(field, "remote_field") +                        and field.remote_field +                        and "__pk" +                        or "" +                    ),                  )                  for field in fields              ] @@ -1763,8 +1770,9 @@ def get_item(              if available:                  for __, jkey, jfield in json_fields:                      if jfield.alt_name not in request_keys: -                        if isinstance(jfield, (forms.NullBooleanField, -                                               forms.BooleanField)): +                        if isinstance( +                            jfield, (forms.NullBooleanField, forms.BooleanField) +                        ):                              my_bool_fields.append(jkey)                              request_keys[jfield.alt_name] = jkey                          else: @@ -1800,7 +1808,7 @@ def get_item(                  continue              key = k[:]              if key.startswith("searchprefix_"): -                key = key[len("searchprefix_"):] +                key = key[len("searchprefix_") :]              dct_request_items[key] = request_items[k]          request_items = dct_request_items @@ -1864,8 +1872,13 @@ def get_item(          if reversed_many_counted_fields:              whole_bool_fields += reversed_many_counted_fields[:]          has_a_search = any( -            k for k in dct.keys() if k not in base_keys and ( -                dct[k] and (k not in whole_bool_fields or dct[k] != '1')) +            k +            for k in dct.keys() +            if k not in base_keys +            and ( +                dct[k] +                and (k not in whole_bool_fields or dct[k] not in ("1", "unknown")) +            )          )          # manage default and pinned search and not bookmark          if ( @@ -2405,7 +2418,7 @@ def adapt_distant_search(params, src, model):                  source=src,                  search_model__model__iexact=model,                  search_keys__contains=[key], -                local_label=value +                local_label=value,              )              up, down = match.span()              if q.count(): @@ -2420,16 +2433,10 @@ def adapt_distant_search(params, src, model):          params["search_vector"] = [final_search_vector] -def get_distant_item( -        request, -        model, -        external_source_id, -        data_type=None -    ): +def get_distant_item(request, model, external_source_id, data_type=None):      # TODO: check permissions      try: -        src = models_rest.ApiExternalSource.objects.get( -            pk=external_source_id) +        src = models_rest.ApiExternalSource.objects.get(pk=external_source_id)      except (models_rest.ApiExternalSource.DoesNotExist, ValueError):          return HttpResponse("{}", content_type="text/plain")      url = src.url @@ -2441,6 +2448,31 @@ def get_distant_item(      if data_type:          params["data_type"] = data_type      adapt_distant_search(params, src, model) + +    default_keys = [ +        "draw", +        "order[", +        "start", +        "length", +        "search[", +        "_", +        "submited", +        "data_type", +    ] +    app = models_rest.MAIN_MODELS[model] +    model_class = ContentType.objects.get(app_label=app, model=model).model_class() +    bool_fields = model_class.REVERSED_BOOL_FIELDS + model_class.BOOL_FIELDS + model_class.CALLABLE_BOOL_FIELDS +    is_empty_params = not any( +        k +        for k in params +        if not any(k for default_key in default_keys if k.startswith(default_key)) +        and (k not in bool_fields or params.get(k) != ["unknown"]) +    ) +    pin_key = "pin-search-" + model +    if ( +        is_empty_params and pin_key in request.session and request.session[pin_key] +    ):  # a search is pinned +        params["search_vector"] = request.session[pin_key]      try:          response = requests.get(              url, @@ -2455,7 +2487,7 @@ def get_distant_item(          for row in dct["rows"]:              if "id" in row:                  try: -                    idx = int(row['id']) +                    idx = int(row["id"])                  except ValueError:                      continue                  source_id = f"source-{external_source_id}-{idx}" @@ -2463,5 +2495,3 @@ def get_distant_item(                  if "link" in row:                      row["link"] = row["link"].replace(str(idx), source_id)      return HttpResponse(json.dumps(dct), content_type="application/json") - -  | 
