python学习交流公众号 Hello Python上线啦,欢迎关注
- 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" #渲染页面
- 对结果集进行筛选可以这样写,利用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
- 模板中
{% for cours in courses %}
<tr>
<td>{{ forloop.counter }}</td>
<td><a href="{% url 'course_detail' cours.id %}">{{ cours.title }}</a></td>
<td>{{ cours.user.username }}</td>
</tr>
{% endfor %}