-
Notifications
You must be signed in to change notification settings - Fork 191
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Support django admin search for binary fields
- Loading branch information
Showing
2 changed files
with
40 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters