Reputation: 65
My view.py is like this
def searchnews(request):
name = request.GET.get('name', 'default')
categry = request.GET.get('category', 'default')
NewTable.objects.filter(headline__contains=name).filter(category=categry)
What I want is that when the value of any element in querystring is empty like if category="" I want to get all the category result
Upvotes: 2
Views: 78
Reputation: 6005
Another option is to build the filter as a kwargs dictionary
kwargs = {'headline__contains': name}
if 'category' in request.GET and request.GET['cateogry'] is not '':
kwargs['category': request.GET['category']
queryset = NewTable.objects.filter(**kwargs)
Upvotes: 1
Reputation: 36181
You can just make a condition to apply the filter
only if a category is provided:
categry = request.GET.get('category', '')
queryset = NewTable.objects.filter(headline__contains=name)
if categry:
queryset = queryset.filter(category=categry)
Upvotes: 0
Reputation: 474141
You can make use of an ability to chain filters in Django.
Set the default to an empty string in case it is not found in request.GET
. Check for not emptiness before adding an additional filter()
:
category = request.GET.get('category', '')
results = NewTable.objects.filter(headline__contains=name)
if category:
results = results.filter(category=category)
Upvotes: 3