from django.shortcuts import render
from .models import Product
from communications.models import Communication
def search(request):
query = request.GET.get('q')
if query:
products = Product.objects.filter(code__icontains=query)
communications = Communication.objects.filter(description__icontains=query)
else:
products = Product.objects.all()
communications = Communication.objects.all()
return render(request, 'search/search.html', {
'query': query,
'products': products,
'communications': communications,
})
Django's Q objects can be used when complex queries are required. Q objects can be used to combine queries with the logical operators | (OR) and & (AND) and the logical negation operator ~. They can be enclosed in parentheses to control the order of evaluation.
Let's say you want to search both in 'name' and 'description' fields of a model. You can do it like this:
from django.shortcuts import render
from .models import Product
from communications.models import Communication
from django.db.models import Q
def search(request):
query = request.GET.get('q')
if query:
products = Product.objects.filter(
Q(name__icontains=query) |
Q(description__icontains=query)
)
communications = Communication.objects.filter(
Q(description__icontains=query)
)
else:
products = Product.objects.all()
communications = Communication.objects.all()
return render(request, 'search/search.html', {
'query': query,
'products': products,
'communications': communications,
})