Treating error in search field with text and integer (Django)

Asked

Viewed 116 times

1

The following code does a value search in the template. But it locates by text, and when I type, for example, 2015 to locate by year, it returns an error because the field must be an integer and not a number, how to treat this error for it to locate by 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 case, when I type a year it works, but when I type another text gives error.

1 answer

1


The ideal is for you to pass a parameter stating what the user wants to search for and to perform a specific filtering, the way the filter is returning any result that contains the searched word, which is not a good practice.

The right thing would be: (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’re doing it is not recommended, you would have to check that q is a year or not, a shape 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) |
)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.