Home > Software design >  Search functionality in list view
Search functionality in list view

Time:04-30

I am trying to implement search functionality in my CBV list view. To do that have I written a "get_queryset". The view looks like this

class List(ListView):
model = Client
...

def get_queryset(self, *args, **kwargs):
    qs = super().get_queryset(*args, **kwargs)
    query = self.request.GET.get('q')
    if query:
        return qs.get(user=query)
    return qs

When I have it like this, I get the following error: "Field 'id' expected a number but got 'x'.". x is in this case whatever I inputed in the search field.

But if I change user to something invalid, I get the following error: "Cannot resolve keyword '' into field. Choices are: user, user_id".

I don't understand why user does not work in this case and why it uses the field "id" if I specify user.

CodePudding user response:

When you use a relational field in your queryset lookup WITHOUT specifying the type of lookup (exact/iexact/icontains,etc.), it assumes that you are querying by exact.

Exact relational lookups allow instances, but will also try using your parameter as an id.

It seems that your user id type is a number/integer, so you have to coerce 'query' to an integer.

If you mean to query something like username, try qs.filter(user__username__icontains=query)

  • Related