Reputation: 61
I have recently implemented a search functionality for Django Web application (it works just fine). However, I do not fully understand the workings of the code. Can you please explain what is going on, and specifically;:
View:
from django.db.models import Q
class ProductListView(ListView):
model = Product
queryset = Product.objects.all()
def get_context_data(self, *args, **kwargs):
context = super(ProductListView, self).get_context_data(*args, **kwargs)
context["now"] = timezone.now()
context["query"] = self.request.GET.get("q") #None
return context
def get_queryset(self, *args, **kwargs):
qs = super(ProductListView, self).get_queryset(*args, **kwargs)
query = self.request.GET.get("q")
if query:
qs = self.model.objects.filter(
Q(title__icontains=query) |
Q(description__icontains=query)
)
try:
qs2 = self.model.objects.filter(
Q(price=query)
)
qs = (qs | qs2).distinct()
except:
pass
return qs
Template
<form class="navbar-form navbar-left" method="GET" role="search" action='{% url "products" %}'>
<div class="form-group">
<input type="text" class="form-control" placeholder="Search" name="q">
</div>
</form>
Upvotes: 0
Views: 61
Reputation: 26
The template tells Django to send a GET request to the backend at the stated url with the param "q" (e.g. www.example.com/products?q=search_term
)
Django matches the url and GET http method to the class ProductListView where q is passed as a param
ListView
inherits from BaseListView
where it sets the context from the method self.get_context_data()
which you extended in your code. BaseListView
inherits from MultipleObjectMixin
which implements the self.get_queryset()
method which you extended as well.
In short CBV (class base views) have a network of inheritance that define their different methods which can be seen here. Many of the methods are hidden from you because of this inheritance chain so you either need to read the docs or better yet study the Django source code to figure out exactly whats happening.
As for return qs, qs is the queryset that you are returning in your extended get_queryset()
method.
ProductListView
Upvotes: 1