Reputation: 2590
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
Upvotes: 0
Views: 1257
Reputation: 8525
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
Upvotes: 1