zoukankan      html  css  js  c++  java
  • Django的ListView超详细用法(含分页paginate功能)

    开发环境:

    python 3.6
    django 1.11

    场景一

    经常有从数据库中获取一批数据,然后在前端以列表的形式展现,比如:获取到所有的用户,然后在用户列表页面展示。

    解决方案

    常规写法是,我们通过Django的ORM查询到所有的数据,然后展示出来,代码如下:

    def user_list(request):
        """返回UserProfile中所有的用户"""
        users = UserProfile.objects.all()
        return render(request, 'talks/users_list.html', context={"user_list": users})
    

    这样能够解决问题,但是Django针对这种常用场景,提供了一个更快速便捷的方式,那就是ListView,用法如下:

    from django.views.generic import ListView
    
    class UsersView(ListView):
    
        model = UserProfile
        template_name = 'talks/users_list.html'
        context_object_name = 'user_list'
    

    这样我们就完成了上边功能,代码很简洁。

    场景二:

    我想要对数据做过滤,ListView怎么实现?代码如下:

    from django.views.generic import ListView
    
    class UsersView(ListView):
    
        model = UserProfile
        template_name = 'talks/users_list.html'
        context_object_name = 'user_list'
        
        def get_queryset(self): # 重写get_queryset方法
        # 获取所有is_deleted为False的用户,并且以时间倒序返回数据
        return UserProfile.objects.filter(is_deleted=False).order_by('-create_time')
    

    如果你要对数据做更多维度的过滤,比如:既要用户是某部门的,还只要获取到性别是男的,这时候,可以使用Django提供的Q函数来实现。

    场景三

    我想要返回给Template的数据需要多个,不仅仅是user_list,可能还有其他数据,如获取当前登陆用户的详细信息,这时怎么操作?,代码如下:

    from django.views.generic import ListView
    
    class UsersView(ListView):
    
        model = UserProfile
        template_name = 'talks/users_list.html'
        context_object_name = 'user_list'
    
        def get_context_data(self, **kwargs):   # 重写get_context_data方法
            # 很关键,必须把原方法的结果拿到
            context = super().get_context_data(**kwargs)
            username = self.request.GET.get('user', None)
            context['user'] = UserProfile.objects.get(username=username
            return context
    

    这样,你返回给Template页面时,context包含为{'user_list': user_list, 'user': user}

    场景四

    我想要限制接口的请求方式,比如限制只能GET访问,代码如下:

    from django.views.generic import ListView
    
    class UsersView(ListView):
    
        model = UserProfile
        template_name = 'talks/users_list.html'
        context_object_name = 'user_list'
        http_method_names = ['GET'] # 加上这一行,告知允许那种请求方式
    

    场景五

    我卡卡卡的返回了所有的数据给前端页面,前页面最好得分页展示呀,这怎么搞?
    欢迎大家到BigYoung小站(bigyoung.cn)查看原文内容。

    本文首发于BigYoung小站

  • 相关阅读:
    彻底解决Spring MVC 中文乱码 问题
    侯捷 c++面向对象程序设计
    folly学习心得(转)
    vcpkg —— VC++ 打包工具
    Windows下安装GCC
    Linux下编写 makefile 详细教程
    侯捷stl学习笔记链接
    《Effective C++(第三版)》-笔记
    CentOS 7 安装Boost 1.61
    Windbg查看w3wp进程占用的内存及.NET内存泄露,死锁分析
  • 原文地址:https://www.cnblogs.com/bigyoung/p/12925786.html
Copyright © 2011-2022 走看看