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

Django查询Post对象报FieldError无法解析followidf字段问题排查

报错原因
  1. followidf 是 followUser 模型中follUser字段定义的反向关联名,仅归属于该外键关联的User模型,不属于Post模型,直接在Post的查询语句中使用followidf作为查询关键字,自然无法被Django ORM识别。
  2. 缺少正确的跨表查询层级:Post和followUser没有直接关联字段,需要按照Post.author(关联User) → User.profile(反向关联Profile一对一表) → Profile.followfp(反向关联followUser表)的路径逐层查询。
修复方案

你需要查询的是当前用户关注的所有作者发布的Post,有两种常用实现方式:

方式1:单语句跨表查询

@login_required
def follow_list(request):
    # 加distinct()避免多表关联产生重复Post
    new2 = Post.objects.filter(author__profile__followfp__follUser=request.user).distinct()
    return render(request, 'accounts/follow_list.html', {'new':  new2  } )

方式2:分步骤查询(性能更直观,无需去重)

@login_required
def follow_list(request):
    # 先取当前用户关注的所有作者ID
    followed_author_ids = followUser.objects.filter(follUser=request.user).values_list('folPr__user_id', flat=True)
    # 过滤出这些作者发布的Post
    new2 = Post.objects.filter(author_id__in=followed_author_ids)
    return render(request, 'accounts/follow_list.html', {'new':  new2  } )

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 18:03:03