applegrew / django-select2

This is a Django integration for Select2

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Support "int" type fields in search_fields in addition to string

cvipul opened this issue · comments

Is your feature request related to a problem? Please describe.
If I add a field in "search_fields" which is of type int, we get
"ValueError: invalid literal for int() with base 10: 'term' "
in the "queryset.filter(select).distinct()" part of filter_queryset

Describe the solution you'd like
Allow for fields to be marked with their type, when specifying the "search_fields" configuration in widget. This would entail taking a dict instead of a list for "search_fields", but its worth it.

Describe alternatives you've considered
I changed the filter_queryset function to convert strings to int for field type integer.
For now I used a "__int" identifier in the field's name.

# current code
# for t in [t for t in term.split(' ') if not t == '']:
#     select &= reduce(lambda x, y: x | Q(**{y: t}), search_fields[1:], Q(**{search_fields[0]: t}))

# updated method
# if field is int type - if term is int -> convert and send - else skip the field for this term
for t in [t for t in term.split(' ') if not t == '']:
    q_string = Q()
    for field in search_fields:
        if field.endswith("__int") and t.isnumeric():
            field = field[:-len("__int")]
            t = int(t)
        elif field.endswith("__int") and not t.isnumeric():
            continue
        q_string |= Q(**{field: t})
    select &= q_string

Looks super shabby in comparison, and might have performance issues, but it works.

Additional context
Search using integers is really helpful as its lighter to index them. Also, in case of unique keys, its a great way for lookup. I am pretty sure someone would have faced this problem, but I couldn't find it in the issues.

@cvipul the idea is cool, but exceeds what this package can offer as this would also require a lot of javascript magic. The main point is, that you are typing in a text field, so guessing if something is an integer or not, is not really something that can be done in a generic way. Which is what this packages aims to provide, a generic why that can be extended. So if you need that functionality, you already know how to implement it in a subclass.