Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor search function #324

Draft
wants to merge 2 commits into
base: dev
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 23 additions & 13 deletions data_models/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -358,25 +358,35 @@ def search_fields():
return ["short_name", "long_name"]

@classmethod
def search(cls, params):
search_type = params.pop("search_type", "plain")
search = params.pop("search", None)
search_fields_param = params.pop("search_fields", None)
if search_fields_param:
search_fields = search_fields_param.split(",")
else:
search_fields = cls.search_fields()
def _parse_custom_search_fields(cls, params):
"""Takes params, typically from a API request, and checks to see if custom
search_fields have been defined. They are spilt and used if present, otherwise
the default search_fields of the class are used.

queryset = cls.objects.all()
Args:
params (dict): {'search_fields': 'short_name,long_name'}. This would
have been enterd in the API request as '?search_fields=short_name,long_name'

Returns:
list: list of field names to search
"""

search_fields = cls.search_fields()
if search_fields_string := params.pop("search_fields", False):
search_fields = search_fields_string.split(",")

if search:
vector = SearchVector(*search_fields)
return search_fields

@classmethod
def search(cls, params):
queryset = cls.objects.all()
if search := params.pop("search", None):
vector = SearchVector(*cls._parse_custom_search_fields(params))
queryset = queryset.annotate(search=vector).filter(
search=SearchQuery(search, search_type=search_type)
search=SearchQuery(search, search_type=params.pop("search_type", "plain"))
)

return queryset.filter(**params)
return queryset.filter(**{k + '__icontains': v for k, v in params.items()})


class Campaign(DataModel):
Expand Down