You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django使用django-taggit时如何统计特定hashtag的关注人数

问题背景

我在项目帖子模块中使用Django-Taggit实现标签功能,帖子模型定义如下:

class Feed(models.Model):
    user = models.ForeignKey(User,
      on_delete=models.CASCADE,related_name='feedposts')
    publish =models.DateTimeField(default = timezone.now)
    created = models.DateTimeField(auto_now_add=True)
    ***
    tags = TaggableManager()

为实现用户关注话题标签(hashtag)的功能,我在用户Profile模型中新增对应字段,模型定义如下:

class Profile(models.Model):
    ****
    following_tags = TaggableManager()

用户关注某个标签时,会将该标签存入following_tags字段。目前已经可以根据用户关注的hashtag拉取对应Feed内容,但需要统计特定hashtag的总关注用户数,暂未找到可行实现方法。
除了放弃django-taggit、自行构建FollowedHashtags关联表的方案外,是否有基于django-taggit的原生实现方式?
自行建表的参考代码如下:

class FollowedHashtags(models.Model):
    name = models.CharField(unique = True)
    user = models.ManyToManyField(User)

该方案下统计hashtag关注人数的实现代码为:

hashtag = FollowedHashtags.objects.get(id=1)
nooffollowers = hashtag.user.count()

我已经尝试过多种过滤查询方法均未得到正确结果,希望得到基于django-taggit的正确实现方式,或是其他更合理的实现方案建议。


回答

基于django-taggit原生的统计实现

Django-Taggit会为每个关联了TaggableManager的模型自动生成对应的中间关联表,不需要手动建表就可以直接统计标签关注人数,核心是通过关联关系做反向查询即可。

具体实现代码

  • 单个标签关注数统计
from taggit.models import Tag
from .models import Profile

# 替换成你要统计的目标标签查询条件,比如按slug、名称筛选
target_tag = Tag.objects.get(slug="target-hashtag-slug")
# 直接过滤出关注了该标签的Profile,统计总数即可
follower_count = Profile.objects.filter(following_tags=target_tag).count()
  • 批量统计所有标签的关注人数
    用聚合查询可以一次拿到所有标签的关注数,避免循环查询产生的N+1性能问题:
from django.db.models import Count
from taggit.models import Tag

tags_with_follower_count = Tag.objects.annotate(
    follower_count=Count('profile_set')
)
# 调用示例:获取第一个标签的关注数
# tags_with_follower_count[0].follower_count

注意:如果你给following_tags字段自定义了related_name参数,把上面代码里的profile_set替换成你自定义的名称即可。

方案选择建议

  • 如果你的标签关注功能只有「关注/取关、统计关注数、拉取关注标签的内容」这几个基础需求,上面的taggit原生方案完全够用,不需要额外建表,维护成本最低。
  • 如果后续你需要给标签关注关系加额外字段,比如关注时间、是否特别关注、关注分组这类属性,也不需要完全放弃django-taggit,只要手动定义自定义中间表,通过through参数传给TaggableManager即可,依然可以复用taggit的所有原生API:
from taggit.managers import TaggableManager
from taggit.models import ItemBase

class FollowedTagRelation(ItemBase):
    profile = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name="tag_follow_relations")
    follow_time = models.DateTimeField(auto_now_add=True) # 自定义扩展字段
    content_object = models.ForeignKey(Profile, on_delete=models.CASCADE)
    
    class Meta:
        unique_together = ('profile', 'tag')

class Profile(models.Model):
    # 其他原有字段
    following_tags = TaggableManager(through=FollowedTagRelation)

内容的提问来源于stack exchange,提问作者Abhey Sharma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 20:45:37