Enable specifying lookup logic

This commit is contained in:
jeremystretch 2022-10-17 16:28:26 -04:00
parent bcc5f6c504
commit eb1557c171
4 changed files with 27 additions and 4 deletions

View File

@ -1,10 +1,19 @@
from django import forms
from django.utils.translation import gettext as _
from netbox.search import LookupTypes
from netbox.search.backends import search_backend
from utilities.forms import BootstrapMixin, StaticSelectMultiple
from utilities.forms import BootstrapMixin, StaticSelect, StaticSelectMultiple
from .base import *
LOOKUP_CHOICES = (
('', _('Partial match')),
(LookupTypes.EXACT, _('Exact match')),
(LookupTypes.STARTSWITH, _('Starts with')),
(LookupTypes.ENDSWITH, _('Ends with')),
)
def build_options(choices):
options = [{"label": choices[0][1], "items": []}]
@ -27,6 +36,13 @@ class SearchForm(BootstrapMixin, forms.Form):
label='Object type(s)',
widget=StaticSelectMultiple()
)
lookup = forms.ChoiceField(
choices=LOOKUP_CHOICES,
initial=LookupTypes.PARTIAL,
required=False,
widget=StaticSelect()
)
options = None
def __init__(self, *args, **kwargs):

View File

@ -14,8 +14,8 @@ class FieldTypes:
class LookupTypes:
EXACT = 'iexact'
PARTIAL = 'icontains'
EXACT = 'iexact'
STARTSWITH = 'istartswith'
ENDSWITH = 'iendswith'

View File

@ -161,7 +161,9 @@ class FilterSetSearchBackend(SearchBackend):
class CachedValueSearchBackend(SearchBackend):
def search(self, request, value, object_types=None, lookup=DEFAULT_LOOKUP_TYPE):
def search(self, request, value, object_types=None, lookup=None):
if not lookup:
lookup = DEFAULT_LOOKUP_TYPE
# Define the search parameters
params = {

View File

@ -163,7 +163,12 @@ class SearchView(View):
app_label, model_name = obj_type.split('.')
object_types.append(ContentType.objects.get_by_natural_key(app_label, model_name))
results = search_backend.search(request, form.cleaned_data['q'], object_types=object_types)
results = search_backend.search(
request,
form.cleaned_data['q'],
object_types=object_types,
lookup=form.cleaned_data['lookup']
)
return render(request, 'search.html', {
'form': form,