首页 > 解决方案 > 如何在 django CB 列表视图中调用具有上下文的函数?

问题描述

这是我的看法:

class viewbloglistview(LoginRequiredMixin,ListView):
    model = Blog
    paginate_by = 6

    def get_template_names(self):
        if True:  
            return ['blog/view_blogs.html']
        else:
            return ['blog/blog_list.html']

    def get_queryset(self):
        return Blog.objects.all().order_by('-blog_views')[:20]

    def get_context_data(self, **kwargs):
        context = super(viewbloglistview, self).get_context_data(**kwargs) 
        context['categories_list'] = categories.objects.all()
        return context

这是我在 models.py 文件中的函数:

    def categories_count(self):
        categories_count = categories.objects.annotate(blog_count=Count('blogs')).values_list('Title','blog_count')
        return categories_count

我想在我的视图中使用上下文名称调用该函数以在我的模板中呈现活动..

谁能帮我解决这个问题??

谢谢

标签: djangodjango-modelsdjango-rest-frameworkdjango-templatesdjango-views

解决方案


假设您已将您的班级命名为“类别”(首先应该将其命名为类别),

当您在班级级别查询时,categories_count 应该已经在经理中。假设您不需要管理器并希望将代码保留在模型中,那么您可以将其用作类方法。

@classmethod
def categories_count(cls):
    return cls.objects.annotate(blog_count=Count('blogs')).values_list('Title','blog_count')

并在视图中将其用作

categories.categories_count()

请记住,像您所拥有的那样带有“self”参数的常规方法只能在处理单个实例时使用,而不是在访问类本身时使用。


推荐阅读