我目前正在尝试将我的FBV代码转换为CBV。通过返回我输入的上下文,get_context_data
运行良好。但是,get_queryset()
由于某种原因返回NOTHING。为了仔细检查,我尝试在返回之前打印search_stores
并打印出应该打印的查询集。但是,当我在Django模板上打印它时,通过键入{{search_stores}},它什么也没显示。我是以错误的方式使用get_queryset
吗?
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
答案 0 :(得分:1)
您的查询集可通过context_object_name
访问。
如果您不提供object_list
,则默认为context_object_name
您可以使用templates
object_list
中的查询集
如果您想更改名称,请更改context_object_name
:
class SearchListView(ListView):
model = Store
template_name = 'boutique/search.html'
context_object_name = 'search_stores'
search_stores
将是可在模板中循环访问的变量