[Feature] Select which fields to search in tables (#13346)

* Allow table search to be limited to selected fields

- Add 'search_fields' query parameter to InvenTreeSearchFilter
- Expose searchable fields (name / label) in the OPTIONS metadata
- Add search field selection menu to the table header

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* Add Playwright test for table search fields

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Add tests for search field restrictions and labels

- Check that search_fields cannot be used to search fields which are
  not exposed for searching by the view
- Check that search field labels are translated based on the request
  language, including a distant related field
- Check the displayed labels in the Playwright test, including a
  distant related field in the BOM table

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Hide the search field menu for tables with a single search field

- Read the searchable fields from the existing table OPTIONS request,
  and cache them alongside the column names
- Only display the search field menu when there is more than one
  field to choose from

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Syogo-SuganoyaandClaude Opus 5.5 authored and GitHub committed 2026-11-25 00:41:45 +11:00
1 parent 9e1e3a9f31
commit 54276081cc
11 files changed
+538 -8

No files matched your search

@@ -1,11 +1,15 @@
"""InvenTree API version information."""
# InvenTree API version
INVENTREE_API_VERSION = 583
INVENTREE_API_VERSION = 584
"""Increment this API version number whenever there is a significant change to the API that any clients need to know about."""
INVENTREE_API_TEXT = """
v584 -> 2026-11-23 : https://github.com/inventree/InvenTree/pull/13346
- Adds "search_fields" query parameter to list endpoints, to limit a search to a subset of the searchable fields
- Adds "search_fields" information to the OPTIONS response for list endpoints
v583 -> 2026-11-20 : https://github.com/inventree/InvenTree/issues/12121
- Adds parameter support to the StockLocationType model and API endpoints
@@ -35,6 +35,7 @@ class InvenTreeSearchFilter(filters.SearchFilter):
The following query params are available to 'augment' the search (in decreasing order of priority)
- search_notes: If True, 'notes' is added to the search_fields if it isn't already present
- search_fields: Comma-separated list of field names, limits the search to a subset of the available search_fields
- search_regex: If True, search is performed on 'regex' comparison
"""
from generic.models.modelmixins import InvenTreeNoteMixin
@@ -71,6 +72,8 @@ class InvenTreeSearchFilter(filters.SearchFilter):
# is returned once per matching note instead of once overall.
self._search_notes_fans_out = notes_field == 'notes_list__content'
search_fields = self.limit_search_fields(search_fields, request)
regex = InvenTree.helpers.str2bool(
request.query_params.get('search_regex', False)
)
@@ -86,6 +89,30 @@ class InvenTreeSearchFilter(filters.SearchFilter):
return fields
@staticmethod
def field_name(field: str) -> str:
"""Return the 'plain' name of a search field, without any DRF lookup prefix."""
return field.lstrip(''.join(filters.SearchFilter.lookup_prefixes.keys()))
def limit_search_fields(self, search_fields, request):
"""Limit the search fields to the subset requested by the 'search_fields' query param.
- Only fields which the view has marked as searchable can be selected
- If no (valid) fields are requested, all search fields are used (default behavior)
"""
requested = request.query_params.get('search_fields', '')
requested = {name.strip() for name in str(requested).split(',') if name.strip()}
if not requested or not search_fields:
return search_fields
limited = [
field for field in search_fields if self.field_name(field) in requested
]
return limited or search_fields
def filter_queryset(self, request, queryset, view):
"""Apply the search filter, then deduplicate if notes search fanned out the join."""
queryset = super().filter_queryset(request, queryset, view)
@@ -161,6 +161,9 @@ class InvenTreeMetadata(SimpleMetadata):
if filters := self.get_filter_metadata(request, view):
metadata['filters'] = filters
if search_fields := self.get_search_field_metadata(view):
metadata['search_fields'] = search_fields
return metadata
@staticmethod
@@ -181,6 +184,69 @@ class InvenTreeMetadata(SimpleMetadata):
getattr(perm, 'allows_any_authenticated_user', False)
)
def get_search_field_metadata(self, view) -> list[dict]:
"""Return information on the fields which can be searched for an API endpoint.
A client can use this to let the user choose which fields a search applies to,
by passing a subset of the field names in the 'search_fields' query parameter.
Returns:
list: A list of {'name', 'label'} entries, one for each searchable field
"""
from InvenTree.filters import InvenTreeSearchFilter
backends = getattr(view, 'filter_backends', None) or []
if not any(
isinstance(backend, type) and issubclass(backend, InvenTreeSearchFilter)
for backend in backends
):
return []
try:
model = view.get_serializer_class().Meta.model
except Exception:
model = None
fields = []
for field in getattr(view, 'search_fields', None) or []:
name = InvenTreeSearchFilter.field_name(field)
fields.append({
'name': name,
'label': self.get_search_field_label(model, name),
})
return fields
def get_search_field_label(self, model, name: str) -> str:
"""Construct a human readable label for a (possibly related) search field.
e.g. 'part__name' -> 'Part / Name' (using the translated field names)
"""
labels = []
for part in name.split('__'):
label = None
if model is not None:
try:
field = model._meta.get_field(part)
label = getattr(field, 'verbose_name', None)
model = getattr(field, 'related_model', None)
except Exception:
# Not a model field (e.g. an annotation) - fall back to the raw name
model = None
if not label:
label = part.replace('_', ' ')
label = str(label)
labels.append(label[:1].upper() + label[1:])
return ' / '.join(labels)
def get_filter_metadata(self, request, view) -> dict:
"""Return information on the choice filters available for an API endpoint.
+175
View File
@@ -682,6 +682,181 @@ class SearchTests(InvenTreeAPITestCase):
# No results again
self.assertEqual(response.data['build']['count'], 0)
def test_search_fields(self):
"""Test that a search can be limited to a subset of fields via 'search_fields'."""
from part.models import Part, PartCategory
TERM = 'zzqxsearchfieldszz'
category = PartCategory.objects.first()
by_name = Part.objects.create(
name=f'{TERM} name', description='Nothing to see', category=category
)
by_desc = Part.objects.create(
name='Unremarkable part', description=f'{TERM} desc', category=category
)
url = reverse('api-part-list')
def search(**kwargs):
response = self.get(url, {'search': TERM, **kwargs}, expected_code=200)
return {part['pk'] for part in response.data}
# Default behavior: all searchable fields are used
self.assertEqual(search(), {by_name.pk, by_desc.pk})
# Limit to a single field
self.assertEqual(search(search_fields='name'), {by_name.pk})
self.assertEqual(search(search_fields='description'), {by_desc.pk})
# Multiple fields (with whitespace)
self.assertEqual(
search(search_fields='name, description'), {by_name.pk, by_desc.pk}
)
# Unknown fields are ignored
self.assertEqual(search(search_fields='name,not_a_field'), {by_name.pk})
# A field which is not searchable cannot be selected:
# falls back to the default search fields
self.assertEqual(
search(search_fields='creation_user__password'), {by_name.pk, by_desc.pk}
)
# Combines with the other search options
self.assertEqual(
search(search_fields='description', search_regex=True), {by_desc.pk}
)
def test_search_fields_restricted(self):
"""Test that 'search_fields' cannot be used to search fields which are not exposed for searching.
The parameter can only narrow the set of searchable fields, never expand it.
"""
from part.api import PartList
from part.models import Part, PartCategory
TERM = 'zzqxrestrictedzz'
searchable = {name.lstrip('^=@$') for name in PartList.search_fields}
# Fields which hold the search term below, none of which are searchable
hidden_fields = [
'link',
'units',
'category__description',
'creation_user__username',
'creation_user__email',
]
for field in hidden_fields:
self.assertNotIn(field, searchable)
user = get_user_model().objects.create_user(
username=f'{TERM}user', email=f'{TERM}@example.com', password='abc123'
)
category = PartCategory.objects.create(
name='Hidden category', description=f'{TERM} category'
)
hidden = Part.objects.create(
name='Hidden part',
description='Nothing to see',
link=f'https://example.com/{TERM}',
units='m',
category=category,
creation_user=user,
)
url = reverse('api-part-list')
def search(term=TERM, **kwargs):
response = self.get(url, {'search': term, **kwargs}, expected_code=200)
return {part['pk'] for part in response.data}
# The term is not found via the default search fields
self.assertNotIn(hidden.pk, search())
# Explicitly requesting a non-searchable field does not search it
for field in hidden_fields:
self.assertNotIn(hidden.pk, search(search_fields=field))
# Combined with a valid field: the non-searchable field is ignored
self.assertNotIn(hidden.pk, search(search_fields='name,link'))
# Lookup prefixes cannot be used to alter the type of lookup performed
for field in ['^name', '=name', '$name', '@name']:
self.assertNotIn(hidden.pk, search(search_fields=f'{field},link'))
def test_search_fields_metadata(self):
"""Test that the searchable fields are exposed via the OPTIONS endpoint."""
from part.api import PartList
response = self.options(reverse('api-part-list'), expected_code=200)
fields = response.data['search_fields']
names = [field['name'] for field in fields]
# Lookup prefixes are not exposed
self.assertEqual(
names, [name.lstrip('^=@$') for name in PartList.search_fields]
)
labels = {field['name']: field['label'] for field in fields}
self.assertEqual(labels['name'], 'Name')
self.assertEqual(labels['description'], 'Description')
self.assertEqual(labels['category__name'], 'Category / Name')
# Labels are translated based on the language of the request
response = self.options(
reverse('api-part-list'),
headers={'Accept-Language': 'de'},
expected_code=200,
)
labels = {
field['name']: field['label'] for field in response.data['search_fields']
}
self.assertEqual(labels['description'], 'Beschreibung')
self.assertEqual(labels['category__name'], 'Kategorie / Name')
# A distant related field, spanning multiple models
labels = {
field['name']: field['label']
for field in self.options(reverse('api-bom-list'), expected_code=200).data[
'search_fields'
]
}
self.assertEqual(
labels['sub_part__category__name'], 'Sub part / Category / Name'
)
response = self.options(
reverse('api-bom-list'),
headers={'Accept-Language': 'de'},
expected_code=200,
)
labels = {
field['name']: field['label'] for field in response.data['search_fields']
}
self.assertEqual(
labels['sub_part__category__name'],
'Untergeordnetes Teil / Kategorie / Name',
)
# A detail endpoint does not provide search information
response = self.options(
reverse('api-part-detail', kwargs={'pk': 1}), expected_code=200
)
self.assertNotIn('search_fields', response.data)
def test_search_notes_distinct(self):
"""Test that search_notes does not return duplicate results for multi-note instances.