Skip to content

Commit

Permalink
feat(apis_entities): add a default search field to the entity filtersets
Browse files Browse the repository at this point in the history
This default search uses `generic.helpers.generate_search_filter` to
either search through all the Char and Textfields or through the fields
the model has defined in `_default_search_fields`.
It uses the same logic to list the searched fields in the help text of
the searchfield.
  • Loading branch information
b1rger committed Aug 13, 2024
1 parent 454090a commit 7cd7906
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions apis_core/apis_entities/filtersets.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,37 @@ def filter(self, queryset, value):
return queryset


class ModelSearchFilter(django_filters.CharFilter):
"""
This filter is a customized CharFilter that
uses the `generate_search_filter` method to
adapt the search filter to the model that is
searched.
It also extracts sets the help text based on
the fields searched.
"""

def __init__(self, *args, **kwargs):
model = kwargs.pop("model", None)
super().__init__(*args, **kwargs)

if model is not None and "help_text" not in self.extra:
if hasattr(model, "_default_search_fields"):
fields = model._default_search_fields
else:
modelfields = model._meta.fields
fields = [
field.name
for field in modelfields
if isinstance(field, (models.CharField, models.TextField))
]
fields = ", ".join(fields)
self.extra["help_text"] = f"Search in fields: {fields}"

def filter(self, qs, value):
return qs.filter(generate_search_filter(qs.model, value))


def related_entity(queryset, name, value):
entities = get_entity_classes()
q = Q()
Expand Down Expand Up @@ -144,6 +175,11 @@ def __init__(self, *args, **kwargs):
self.filters["related_property"] = PropertyFilter(
label="Related Property", model=getattr(self.Meta, "model", None)
)

if model := getattr(self.Meta, "model", False):
self.filters["search"] = ModelSearchFilter(model=model)
self.filters.move_to_end("search", False)

if "apis_core.history" in settings.INSTALLED_APPS:
self.filters["changed_since"] = django_filters.DateFilter(
label="Changed since",
Expand Down

0 comments on commit 7cd7906

Please sign in to comment.