Treating search field error with text and integer (Django)

1

The following code searches for values in the template. But it finds by text, and when I type, for example, 2015 to find by year, it returns an error because the field must be an integer and not a number, how to handle this error so that it finds the year? >

p = Proposal.objects.all().select_related()
q = self.request.GET.get('search_box')
if not q in [None, '']:
    p = p.filter(
        Q(id__icontains=q) |
        Q(work__name_work__icontains=q) |
        Q(work__customer__first_name__icontains=q) |
        Q(category__category__startswith=q) |
        Q(employee__user__first_name__startswith=q) |
        Q(seller__employee__user__first_name__startswith=q) |
        Q(created__year=q)
    )

See the error:

ValueError at /proposal/
The __year lookup type requires an integer argument

In the case, when I type one year it works, but when I type another text it gives error.

    
asked by anonymous 31.07.2015 / 18:57

1 answer

1

The ideal thing is to pass a parameter informing what the user wants to fetch and thus perform a specific filtering, the way the filter is is returning any result that contains the searched word, which is not a good practice.

The right thing to do: (passing information through the template)

especifico_por = request.GET.get('especifico', False)
if especifico_por == 'ano':
    p = p.filter(created__year=q)
elif especifico_por == 'cliente':
    p = p.filter(work__customer__first_name__icontains=q)
# e assim por diante...

The way you are doing is not recommended , you would have to check if this q is a year or not, a form would be using exception :

try:
     p = p.filter(created__year=q)
except TypeError:
     pass

p = p.filter(
    Q(id__icontains=q) |  # id__icontains não faz sentido algum
    Q(work__name_work__icontains=q) |
    Q(work__customer__first_name__icontains=q) |
    Q(category__category__startswith=q) |
    Q(employee__user__first_name__startswith=q) |
    Q(seller__employee__user__first_name__startswith=q) |
)
    
31.07.2015 / 20:48