Django报错'TaggableManager'无'get_reverse_joining_fields'属性求助
解决TaggableManager检索相似文章的报错问题
错误原因
报错'TaggableManager' object has no attribute 'get_reverse_joining_fields'是因为直接对django-taggit的TaggableManager使用Count('tags')聚合时,该管理器不支持这种直接操作,需要调整查询逻辑。
修正后的代码
from django.db.models import Count from django.shortcuts import get_object_or_404, render def post_detail(request, id): post = get_object_or_404(Post, status=Post.Status.PUBLISH, id=id) post_tags_ids = post.tags.values_list('id', flat=True) # 调整聚合方式,添加distinct=True避免重复计数,修正拼写错误pblish→publish similar_posts = ( Post.objects.filter(tags__in=post_tags_ids) .exclude(id=post.id) .annotate(same_tags=Count('tags', distinct=True)) .order_by('-same_tags', '-publish')[:4] ) comments = post.comments.filter(active=True) form = commentForm() return render(request, 'blog/post/detail.html', context={ "post": post, 'comments': comments, 'form': form, 'similar_posts': similar_posts })
备选方案(通过中间表查询)
如果上述方法仍有问题,可以直接使用taggit的中间表TaggedItem来构建查询:
from taggit.models import TaggedItem from django.db.models import Count def post_detail(request, id): post = get_object_or_404(Post, status=Post.Status.PUBLISH, id=id) post_tags_ids = post.tags.values_list('id', flat=True) # 先通过TaggedItem获取关联的文章ID,再查询文章并统计标签数 related_post_ids = TaggedItem.objects.filter(tag_id__in=post_tags_ids)\ .exclude(object_id=post.id)\ .values_list('object_id', flat=True) similar_posts = ( Post.objects.filter(id__in=related_post_ids) .annotate(same_tags=Count('tags', distinct=True)) .order_by('-same_tags', '-publish')[:4] ) comments = post.comments.filter(active=True) form = commentForm() return render(request, 'blog/post/detail.html', context={ "post": post, 'comments': comments, 'form': form, 'similar_posts': similar_posts })
注意事项
- 修正了原代码中的拼写错误:
-pblish改为-publish,否则会引发字段不存在的错误 - 添加
distinct=True是为了避免同一文章因多个相同标签被重复计数,保证统计结果准确
内容的提问来源于stack exchange,提问作者mkg
相关产品推荐
相关产品推荐

