[Fixed]-Understanding this Django search functionality

1πŸ‘

βœ…

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.

  • Your taking the value q
  • Filtering for any model that has the value of q in the title or description and storing it as a queryset in qs
  • Filtering for any model that has a price of q and storing it as a queryset in qs2
  • Combining querysets qs and qs2 and making sure each record is unique, then returning that queryset to be the queryset used by ProductListView
πŸ‘€kobeham

Leave a comment