Django开发带帖子点赞功能的Web应用时点击Like按钮报DoesNotExist错误
Django 点赞功能
DoesNotExist异常排查 故障表现
开发带帖子点赞交互的Web应用时,项目整体运行逻辑正常,但点击Like按钮触发交互、或是访问/posts/liked路径加载页面时,会抛出DoesNotExist异常,现有代码片段如下:
Like模型定义
class Like(models.Model): user = models.ForeignKey(Yatru, on_delete=models.CASCADE) location = models.ForeignKey(Post, on_delete=models.CASCADE) value = models.CharField(choices=LIKE_CHOICES, max_length=8) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.user}-{self.location}-{self.value}"
点赞/取消逻辑视图like_unlike
def like_unlike(request): user = request.user if request.method == 'POST': location_id = request.POST.get('location_id') location_obj = Post.objects.get(id=location_id) profile = Yatru.objects.get(user=user) if profile in location_obj.liked.all(): location_obj.liked.remove(profile) else: location_obj.liked.add(profile) like, created = Like.objects.get_or_create(user=profile, location_id=location_id) if not created: if like.value=='Like': like.value='Unlike' else: like.value='Like' location_obj.save() like.save() return redirect('posts:post_views')
根本原因定位
DoesNotExist是Django ORM执行get()查询时,未匹配到符合条件的数据抛出的标准异常,结合现有代码可定位到几处直接触发的场景:
Yatru.objects.get(user=user):当前视图没有显式校验登录状态,未登录的匿名用户发起请求时,request.user是匿名对象,执行该查询会直接抛出异常;就算是已登录用户,如果没有关联的Yatru档案,也会触发该错误。若/posts/liked路径的视图直接依赖当前用户的Yatru档案做查询,没有匹配档案的用户、或是未登录用户访问时,页面加载就会触发报错。Post.objects.get(id=location_id):如果POST请求传递的location_id为空、或是对应ID的帖子已被删除,执行该查询无法匹配到数据,就会抛出Post.DoesNotExist异常。- 未贴出的
/posts/liked视图代码如果直接查询当前用户的Like关联记录,当用户没有对应Yatru档案、或关联Like数据被级联删除时,也会触发查询失败报错。 - 逻辑冲突点:现有代码同时维护了Post的
liked多对多字段、独立Like表两套点赞数据,两套逻辑不同步时也可能出现查询不到预期数据的问题。
内容的提问来源于stack exchange,提问作者BhShr
相关产品推荐
相关产品推荐

