Skip to content

Commit

Permalink
Stb#537 Fix field types determination for Search class (#315)
Browse files Browse the repository at this point in the history
* Fix field types determination for Search class

* Fix typo

* Remove dangling line

* Apply review fixes
  • Loading branch information
ArtemijRodionov authored Mar 29, 2019
1 parent 19d6343 commit e49a28b
Showing 1 changed file with 25 additions and 11 deletions.
36 changes: 25 additions & 11 deletions search/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,26 @@ def trigram_search(query: str, queryset, fields: List[str]):
return queryset.annotate(similarity=trigram_query).order_by('-similarity')


def get_field_type(model, field):
"""
Determine a type name of Django field.
@todo #stb-537:30m Create a class instead this function.
See there for details: https://github.com/fidals/refarm-site/pull/315/files#r270500698
"""
if '__' in field:
# translate `product__name` to `name` and swap `model` to `Product`
model_name, field = field.split('__')
model = model._meta.get_field(model_name).related_model

return (
model._meta
.get_field(field)
.get_internal_type()
)


class Search:
def __init__(
self, name, qs, fields,
Expand All @@ -59,8 +79,8 @@ def __init__(
:param fields: list of query lookups
:param template_fields: list fields for django templates
:param min_similarity: used to trigram similarity search
:param redirect_field: when client search for this field, the result is
redirected to custom page
:param redirect_field: when client search for this field, the result is
redirected to custom page
"""
self.name = name
self.fields = fields
Expand All @@ -73,22 +93,16 @@ def __init__(
self.decimal_fields = []

for field in fields:
field_type = (
self.qs.model._meta
.get_field(field.partition('__')[0])
.get_internal_type()
)
if field_type in ['CharField', 'TextField']:
type_ = get_field_type(self.qs.model, field)
if type_ in ['CharField', 'TextField']:
# Trigram similarity supports only these two entity types
self.trigram_fields.append(field)
else:
self.decimal_fields.append(field)

def search(self, term: str):
def _trigram_search(query):
"""
Just a shortcut for trigram_search function call
"""
"""Just a shortcut for trigram_search function call."""
return trigram_search(query, self.qs, self.trigram_fields).filter(
similarity__gt=self.min_similarity
)
Expand Down

1 comment on commit e49a28b

@0pdd
Copy link
Collaborator

@0pdd 0pdd commented on e49a28b Mar 29, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Puzzle stb-537-a8b24119 discovered in search/search.py and submitted as #316. Please, remember that the puzzle was not necessarily added in this particular commit. Maybe it was added earlier, but we discovered it only now.

Please sign in to comment.