ListView

from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import ListView

from apps.news.models import News


class NewsListView(LoginRequiredMixin, ListView):
    '''首页动态'''
    model = News
    paginate_by = 20  # 每一页显示的数目 url中?page=
    page_kwarg = 'p'  # 自定义url ?p= 条数
    context_object_name = 'news_list'  # 默认值是'模型类名_list'或者'objec_list
    ordering = ('-crated_at', )  # 按照某个字段排序
    template_name = 'news/news_list.html'    # 指定模板
    queryset = News.objects.all()  # 返回的查询集

    def get_ordering(self):
        '''复杂排序 推荐'''
        pass

    def get_paginate_by(self, queryset):
        '''复杂的分页逻辑
        queryset 是查询集
        '''
        pass

    def get_queryset(self, **kwargs):
        '''返回 数据在查询集'''
        return News.objects.filter(reply=False)

    def get_context_data(self, *, object_list=None, **kwargs):
        '''覆盖这个方法可以推荐额外的上下文'''
        countext = super().get_context_data()
        countext['count'] = 100
        return countext

模板中使用

{% for news in news_list %}