Django判断标签使用次数触发通知时报'Tag' object has no attribute 'count'
错误原因
- 你已经通过
annotate为每个返回的Tag实例新增了统计字段num_name,遍历查询集时拿到的是单个Tag对象,不是查询集,因此没有count()方法,也不能用len()直接统计。 - 你的统计逻辑有误:
Count('name')是统计标签名的数量(同一个标签名只会统计为1),你需要统计的是当前标签关联的Post数量,应该统计关联的post字段。 - 原代码存在语法遗漏:
annotate方法缺少闭合括号,return语句的context字典缺少闭合括号。
修正代码
def page(request): # 统计每个标签被当前用户的Post使用的次数 tag_query = Tag.objects.filter(post__post_user=request.user).annotate( use_count=Count('post', distinct=True) # 用distinct避免重复关联数据干扰统计 ) for tag in tag_query: if tag.use_count >= 10: # 可加判断避免重复创建通知,比如判断该标签的通知是否已存在 if not Notification.objects.filter(user=request.user, tag=tag).exists(): Notification.objects.create(user=request.user, tag=tag) context = {'subquery': tag_query} return render(request, 'page.html', context)
优化方案(可选)
如果不需要把全量标签统计数据传给模板,你可以直接在查询阶段过滤出使用次数达标的标签,减少循环开销:
def page(request): # 直接过滤出使用次数>=10的标签 hit_tags = Tag.objects.filter(post__post_user=request.user)\ .annotate(use_count=Count('post', distinct=True))\ .filter(use_count__gte=10) for tag in hit_tags: if not Notification.objects.filter(user=request.user, tag=tag).exists(): Notification.objects.create(user=request.user, tag=tag) # 仍需传给模板的全量标签统计数据 all_tags = Tag.objects.filter(post__post_user=request.user).annotate(use_count=Count('post', distinct=True)) context = {'subquery': all_tags} return render(request, 'page.html', context)
内容的提问来源于stack exchange,提问作者Lars
相关产品推荐
相关产品推荐

