You need to enable JavaScript to run this app. Django返回评论Model查询结果为JSON时如何获取关联用户外键字段值
优惠活动
大模型
产品
解决方案
定价
更多

Django返回评论Model查询结果为JSON时如何获取关联用户外键字段值

错误原因说明

  1. 你修改后的views.py里"commented_by": commented_by写法错误,缺少前缀comment.属于未定义变量,直接触发运行报错
  2. Django的serializers.serialize方法仅支持序列化Django模型实例的查询集,你手动拼接的普通字典列表无法用该方法序列化

可用解决方案

方案1:直接用values指定关联字段(最简单)

通过Django ORM双下划线语法直接查询关联用户表的字段,无需额外循环处理:

def load_comments(request, post_id):
    """Returns the comments to index.js"""
    try:
        post = Post.objects.get(pk=post_id)
        # 需要用户的什么字段就添加对应的双下划线字段即可
        comments = list(Comment.objects.filter(post=post).values(
            "comment",
            "commented_by__id",
            "commented_by__username"
        ))
        return JsonResponse({"comments": comments})
    except Post.DoesNotExist:
        # 指定捕获异常类型比裸except更安全,同时设置正确的HTTP状态码
        return JsonResponse({"error": "Post not found", "status": 404}, status=404)

对应JS取值写法:

b.textContent = comment.commented_by__username + " ";

方案2:手动拼接返回字典(更灵活,推荐)

搭配select_related做连表查询优化,避免N+1查询问题,可自定义返回数据结构:

def load_comments(request, post_id):
    """Returns the comments to index.js"""
    try:
        post = Post.objects.get(pk=post_id)
        # select_related提前加载关联用户数据,避免循环时重复查询数据库
        post_comments = Comment.objects.filter(post=post).select_related("commented_by")
        
        comments = []
        for comment in post_comments:
            comments.append({
                "comment": comment.comment,
                "commented_by": {
                    "id": comment.commented_by.id,
                    "username": comment.commented_by.username
                    # 需要其他用户字段直接在这里添加即可
                }
            })
        return JsonResponse({"comments": comments})
    except Post.DoesNotExist:
        return JsonResponse({"error": "Post not found", "status": 404}, status=404)

对应JS取值写法:

b.textContent = comment.commented_by.username + " ";

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 17:36:07