回到顶部

Contents

django ListView 获取 url 中的参数及根据参数使用不同的模板

from django.views import generic


class IndexView(generic.ListView):
    template_name = 'lw-index-noslider.html'  # 默认加载该模板文件
    context_object_name = "articles"  # 是数据库搜索出来的结果存放的变量名字,用于模板循环显示
    paginate_by = paginate_by  # 设置分页中每一页的记录数目
    model = Article  # 定义从哪份model中查询


    def get_queryset(self):
        """Return the last five published questions."""
  
        req_get_dict = self.request.GET.dict()
        if req_get_dict:
            # 记录 get 请求参数
            logger.info(req_get_dict)
            
        req_get_dict_ordering = req_get_dict.get("ordering", None)
        if req_get_dict_ordering:
            if req_get_dict_ordering == "view":
                self.template_name = "index_view.html"  # 指定要渲染的模板
                articles = cache.get("article_views_rank")
                if not articles:
                    # article_views_rank = Article.objects.order_by("-num_views")  # 旧浏览量
                    articles = ArticleViewPage.objects.order_by("-view_page")
                    cache.set("article_views_rank", articles, CACHE_TIMEOUT_1H)
                self.ordering = "view"
            elif req_get_dict_ordering == "-view":
                self.template_name = "index_view.html"  # 指定要渲染的模板
                articles = cache.get("article_views_rank_reverse")
                if not articles:
                    # article_views_rank = Article.objects.order_by("-num_views")  # 旧浏览量
                    articles = ArticleViewPage.objects.order_by("view_page")
                    cache.set("article_views_rank_reverse", articles, CACHE_TIMEOUT_1H)
                self.ordering = "-view"
            else:
                articles = cache.get("articles_top")
                if not articles:
                    articles = Article.objects.filter(show_status=True).order_by('-is_top', '-time_created')
                    cache.set("articles_top", articles, CACHE_TIMEOUT_1H)
                self.ordering = "ctime_top"                
        eles:
            articles = cache.get("articles_top")
            if not articles:
                articles = Article.objects.filter(show_status=True).order_by('-is_top', '-time_created')
                cache.set("articles_top", articles, CACHE_TIMEOUT_1H)
            self.ordering = "ctime_top"
        
        return articles

 


^_^
请喝咖啡 ×

前一篇: 如何选择合适的 django 版本使用
下一篇: linux(centos)各种颜色文件的含义
captcha