Python Django仿Twitter项目:关注者计数功能实现失败求助
问题分析与修复方案
核心问题1:未定义的id变量
你用于计算关注者数量的代码中,followed_by=id里的id是未定义的变量,这会直接导致代码运行报错。
核心问题2:粉丝计数逻辑错误
假设你的Follower模型用following字段存储被关注的用户,followed_by存储发起关注的用户,那统计某个用户的粉丝数,应该是统计有多少用户(followed_by)关注了该用户(following=当前用户),而非原代码中的反向过滤。
修复后的视图代码
def get_context_data(self, **kwargs): user = self.get_object() context = super().get_context_data(**kwargs) context['total_posts'] = Post.objects.filter(author=user).count() # 修复:使用正确的过滤条件统计当前用户的粉丝数 context['total_followers'] = Follower.objects.filter(following=user).count() if self.request.user.is_authenticated: context['you_follow'] = Follower.objects.filter(following=user, followed_by=self.request.user).exists() return context
补充:确认Follower模型结构
如果你的Follower模型尚未正确定义,可参考以下标准结构:
class Follower(models.Model): following = models.ForeignKey(User, on_delete=models.CASCADE, related_name='followers') followed_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='following') created_at = models.DateTimeField(auto_now_add=True) class Meta: unique_together = ('following', 'followed_by') # 限制同一用户不能重复关注
内容的提问来源于stack exchange,提问作者Alyssa
相关产品推荐
相关产品推荐

