django中类视图ListView的使用

  1. ListView 用于获取数据表中的所有数据,返回一个列表。
from django.views.generic import ListView
from course.models import Course
class CourseListView(ListView):
    """通用视图"""
    model = Course     #指定类
    context_object_name = 'courses'    #courses被传到模板中
    template_name = "course/course_list.html"  #渲染页面
  1. 对结果集进行筛选可以这样写,利用Q组合查询,还可以用get_context_data方法,传给模板额外的数据,参考官方文档
from django.db.models import Q
class CourseListView(ListView):
    """通用视图"""
    template_name = "course/course_list.html"  #渲染页面
    def get_queryset(self):
        courses = Course.objects.filter(
            Q(name='python') |
            Q(description__contains='python')
        )
        return courses
   
  1. 模板中
{% for cours in courses %}
    
        {{ forloop.counter }}
        {{ cours.title }}
        {{ cours.user.username }}
    
{% endfor %}

你可能感兴趣的:(Django)