vikrant
vikrant

Reputation: 81

stuck in implementing search in django

I want to implement search in django. I don't use any search technique like solar etc. I am using simple filter query of django. Now the problem is this: I have a model Product with five field name, cost, brand, expiry_date, weight I want to implement a advanced search feature with all fields, by:

name = request.GET.get('name')

I get a value on which basis I search all product. What I want is that when name = None, it has to search for all names. So problem is this: if values are not coming by user side, how can i search for all names?

Upvotes: 1

Views: 177

Answers (3)

Moses Koledoye
Moses Koledoye

Reputation: 78536

You didn't show your search query. However, I think using contains (or icontains for case insensitive match) will help you solve the problem, with the benefit of being able to search for say first names, last names and names containing a matching text.

You would do:

name = request.GET.get('name', '')
search_result = Product.objects.filter(name__icontains=name)

Notice the get method has been instructed to return a '' instead of the default None. And keep in mind that all strings in Python contain the empty string ''. So when no name is sent via the request, every Product in the DB (with a not NULL name) is returned, as their names all contain the empty string ''.

Upvotes: 1

Dawn T Cherian
Dawn T Cherian

Reputation: 5406

Try this:

result = Product.objects.all()
name = request.GET.get('name', None)
if name:
    result = result.objects.filter(name__icontains=name)

Upvotes: 0

Bharat Kotwani
Bharat Kotwani

Reputation: 119

if you want when the name is None, you have to search all names in Product Model try this logic

if name == None:
    result = Product.objects.all()
else:
    result = Product.objects.filter(name = name)

Upvotes: 0

Related Questions