如何在Django中的get_queryset()中返回一个查询集

时间:2018-05-08 02:13:10

标签: django

我目前正在尝试将我的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

1 个答案:

答案 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将是可在模板中循环访问的变量