I've written an index and search view all in one if a GET request is detected it returns just the search results otherwise it returns all records. I've written this view below but I feel like I'm repeating myself a bit too much. Any ideas as to how I can slim this code down a bit would be much appreciated.
def index(request):
if 'q' in request.GET:
company_list = Company.objects.filter(
Q(company__icontains = request.GET['q']) |
Q(county__icontains = request.GET['q']) |
Q(city__icontains = request.GET['q']) |
Q(product_description__icontains = request.GET['q'])
)
query = request.GET['q']
else:
company_list = Company.objects.all()
paginator = Paginator(company_list, 10)
try:
page = int(request.GET.get('page', '1'))
except ValueError:
page = 1
try:
companies = paginator.page(page)
except (EmptyPage, InvalidPage):
companies = paginator.page(paginator.num_pages)
if 'q' in request.GET:
return render_response(request, 'database/index.html', {"companies": companies, "query": query})
else:
return render_response(request, 'database/index.html', {"companies": companies})