功能:
- 分页,排序
- 讲师详情(有哪些课程,属于哪个机构,讲师排行榜)
url配置:
# 教师列表
url(r'^teacher/list/$', TeacherListView.as_view(), name='teacher_list'),
# 教师详情页
url(r'^teacher/detail/(?P<teacher_id>\d+)/$', TeacherDetailView.as_view(), name='teacher_detail'),
讲师列表页
class TeacherListView(View):
def get(self, request):
all_teachers = Teacher.objects.all()
sort = request.GET.get('sort', '')
teacher_nums = all_teachers.count()
# 搜索
keyword = request.GET.get('keywords', '')
if keyword:
# i表示忽略大小写
all_teachers = all_teachers.filter(
Q(name__icontains=keyword) | Q(work_position__icontains=keyword))
if sort:
if sort == 'hot':
all_teachers = all_teachers.order_by('-click_nums')[:3]
# 讲师排行榜
sorted_teacher = Teacher.objects.all().order_by('-click_nums')[:3]
# 分页处理
try:
page = request.GET.get('page', 1)
except PageNotAnInteger:
page = 1
p = Paginator(all_teachers, 2, request=request)
teachers = p.page(page)
return render(request, 'teachers-list.html',
{'all_teachers': teachers,
'teacher_nums': teacher_nums,
'sorted_teacher': sorted_teacher})
讲师详情页
class TeacherDetailView(View):
def get(self, request, teacher_id):
teacher = Teacher.objects.get(id=int(teacher_id))
# 点击数加一
teacher.click_nums += 1
teacher.save()
all_course = Course.objects.filter(teacher=teacher)
sorted_teacher = Teacher.objects.all().order_by('-click_nums')[:3]
# 教师和机构是否收藏
has_teacher_faved = False
has_org_faved = False
if UserFavorite.objects.filter(user=request.user, fav_type=3, fav_id=teacher.id):
has_teacher_faved = True
elif UserFavorite.objects.filter(user=request.user, fav_type=2, fav_id=teacher.org.id):
has_org_faved = True
return render(request, 'teacher-detail.html',
{'teacher': teacher,
'all_course': all_course,
'sorted_teacher': sorted_teacher,
'has_teacher_faved': has_teacher_faved,
'has_org_faved': has_org_faved})