0

I'm currently trying to convert my FBV codes to CBV. get_context_data is working well by returning contexts that I put in. However, get_queryset() returns NOTHING for some reason. To double-check, I tried to print search_stores right before returning it and it printed the queryset that is supposed to be printed. However, when I printed it on Django template, by typing {{ search_stores }}, it shows nothing. Am I using get_queryset in a wrong way?

class SearchListView(ListView):
    model = Store
    template_name = 'boutique/search.html'
    # paginate_by = 5

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['search_text'] = self.request.GET.get('search_text')
        context['sorter'] = self.request.GET.get('sorter')
        if not context['sorter']:
            context['sorter'] = 'popularity'
        return context

    def get_queryset(self):

        search_text = self.request.GET.get('search_text')
        sorter = self.request.GET.get('sorter')

        if search_text:
            search_stores = Store.objects.filter(Q(businessName__icontains=search_text) | Q(mKey__icontains=search_text))
            if sorter == 'businessName':
                search_stores = search_stores.order_by(sorter)
            else:
                search_stores = search_stores.order_by(sorter).reverse()
        else:
            search_stores = ''

        for store in search_stores:
            store.mKey = store.mKey.split(' ')

        print(search_stores)
        return search_stores

1 Answer 1

1

Your queryset is accessible via the context_object_name. By default it's object_list if you don't provide context_object_name
You can access the queryset in templates with object_list

If you want to change the name, change the context_object_name:

class SearchListView(ListView):
   model = Store
   template_name = 'boutique/search.html'
   context_object_name = 'search_stores'

search_stores will be the variable accessible to loop through in templates

Sign up to request clarification or add additional context in comments.

4 Comments

glad to be of help!
I just have a minor question. Is it possible to return multiple query sets in get_queryset()?
get_queryset is only for the Model belongs to the CBV, if you want to send multiple queryset, you can do so in get_context_data()
ok then if I wanna use pagination on a specific queryset, that queryset must be returned from get_queryset. Is that correct?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.