From f51fc5ea51c84ef975c7b9dff66e4b86bb59ef93 Mon Sep 17 00:00:00 2001 From: Uxio Fuentefria Date: Tue, 15 Mar 2022 12:10:15 +0100 Subject: [PATCH] Support django admin search for binary fields --- gnosis/eth/django/admin.py | 39 ++++++++++++++++++++++++++++++++++++++ setup.py | 2 +- 2 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 gnosis/eth/django/admin.py diff --git a/gnosis/eth/django/admin.py b/gnosis/eth/django/admin.py new file mode 100644 index 000000000..dcc7c2141 --- /dev/null +++ b/gnosis/eth/django/admin.py @@ -0,0 +1,39 @@ +from typing import Tuple + +from django.contrib import admin +from django.core.exceptions import ValidationError +from django.db.models import QuerySet +from django.http import HttpRequest + + +class BinarySearchAdmin(admin.ModelAdmin): + """ + Search inside binary fields, like EthereumAddressV2Field or Keccack256Field + """ + + def get_search_results( + self, request: HttpRequest, queryset: QuerySet, search_term: str + ) -> Tuple[QuerySet, bool]: + queryset, may_have_duplicates = super().get_search_results( + request, queryset, search_term + ) + if search_term: + for search_field in self.get_search_fields(request): + try: + if search_field.startswith("="): + may_have_duplicates = True + queryset |= self.model.objects.filter( + **{search_field[1:]: search_term} + ) + elif search_field.endswith("__icontains"): + may_have_duplicates = True + queryset |= self.model.objects.filter( + **{ + search_field.replace("__icontains", "__contains"): [ + search_term + ] + } + ) + except (ValidationError, ValueError): + pass + return queryset, may_have_duplicates diff --git a/setup.py b/setup.py index 6984b45c9..a3417c2ae 100644 --- a/setup.py +++ b/setup.py @@ -22,7 +22,7 @@ setup( name="gnosis-py", - version="3.8.1", + version="3.8.2", packages=find_packages(), package_data={"gnosis": ["py.typed"]}, install_requires=requirements,