前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >django ListView 获取 url 中的参数及根据参数使用不同的模板

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

作者头像
卓越笔记
发布2023-02-18 13:52:05
3.4K0
发布2023-02-18 13:52:05
举报
文章被收录于专栏:卓越笔记
代码语言:javascript
复制
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
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-12-25 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档