django - 如何在 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
我想在我的视图中使用上下文名称调用该函数以在我的模板中呈现活动..
谁能帮我解决这个问题??
谢谢
解决方案
假设您已将您的班级命名为“类别”(首先应该将其命名为类别),
当您在班级级别查询时,categories_count 应该已经在经理中。假设您不需要管理器并希望将代码保留在模型中,那么您可以将其用作类方法。
@classmethod
def categories_count(cls):
return cls.objects.annotate(blog_count=Count('blogs')).values_list('Title','blog_count')
并在视图中将其用作
categories.categories_count()
请记住,像您所拥有的那样带有“self”参数的常规方法只能在处理单个实例时使用,而不是在访问类本身时使用。
推荐阅读
- python - 如何在 pandas 的同一个 Excel 列表中组合来自不同表的数据?
- android - 检测应用程序是否从华为应用市场安装
- python-3.x - XML 日志文件打印到漂亮
- javascript - JavaScript IntersectionObserver rootMargin 不起作用
- python - 使用两个相同的列信息,合并第三列
- r - 如何从多个 .txt 文件创建小标题,在列中保留文件名,以及使用文件名将文件分类?
- java - 找不到 org.springframework.boot:spring-boot-starter-cloud-connectors
- flutter - 如何在 Flutter 中的 ExpansionPanellist 中给出扩展面板之间的间距?
- php - 没有定义外键约束的雄辩关系
- linux - Linux删除第一行空格